如何在 PostgreSQL 中合并两个查询?
Posted
技术标签:
【中文标题】如何在 PostgreSQL 中合并两个查询?【英文标题】:How to merge two queries in PostgreSQL? 【发布时间】:2018-12-10 12:51:10 【问题描述】:我想在 PostgresSQL 中编写一个查询,返回给定日期范围内的月销售额。
我有 2 个查询 - 1 个返回销售计数,另一个返回按日期范围(开始日期和结束日期)列出的月份列表
查询 1:(返回销售计数)
SELECT count(overall_sl) total_sales, count(CASE WHEN overall_sl < value_1 THEN 1 END) faled_sales
FROM (
SELECT overall_sl, value_1
FROM combined c
GROUP BY dept_name, date_updated, date, overall_sl, no_addons,
value_1, category_id, subcategory_id, branch_name
) sales;
Output:
total sales failed_sales
----------------------------
1047 54
查询 2:(返回给定两个日期的月份列表)
WITH date_ranges AS (
SELECT
min(date_trunc('month', timestamp '2018-01-01')) min_start,
max(date_trunc('month', timestamp '2018-12-11')) max_end
)
SELECT
ser.month::DATE as st_month,
(date_trunc('month', ser.month::DATE) + interval '1 month' - interval '1 day')::date as end_month,
0 as total_sales,
0 as failed_sales
FROM date_ranges AS dr,
generate_series(min_start, max_end, '1 month') AS ser(month)
Output:
st_date end_date total_sales failed_sales
---------- ---------- ---------- ------------
2018-01-01 2018-01-31 0 0
2018-02-01 2018-02-28 0 0
我需要加入这些查询,如下图所示
如何在 Postgres SQL 中编写此查询?
【问题讨论】:
【参考方案1】:你可以试试下面的
with cte as
(
SELECT count(overall_sl) total_sales, count(CASE WHEN overall_sl < value_1 THEN 1 END) faled_sales
FROM (
SELECT overall_sl, value_1
FROM combined c
GROUP BY dept_name, date_updated, date, overall_sl, no_addons,
value_1, category_id, subcategory_id, branch_name
) sales
),
date_ranges AS
(
SELECT
min(date_trunc('month', timestamp '2018-01-01')) min_start,
max(date_trunc('month', timestamp '2018-12-11')) max_end
),
cte2 as
(
SELECT
ser.month::DATE as st_month,
(date_trunc('month', ser.month::DATE) + interval '1 month' - interval '1 day')::date as end_month,
0 as total_sales,
0 as failed_sales
FROM date_ranges AS dr,
generate_series(min_start, max_end, '1 month') AS ser(month)
) select cte.*,cte2.* from cte join cte2 on cte.total_sales=cte2.total_sales and cte.failed_sales=cte2.failed_sales
【讨论】:
感谢您的快速回复。但是当我运行这个查询时我没有得到任何结果:( 0 as total_sales, 0 as failed_sales -- 是实际值应该出现的占位符 @Showkath 使用你没有得到任何结果,因为只有当两个表中都存在公共键时,内连接才返回,因为你没有提到你的组合输出,所以我不知道你的连接是左、右还是内 恐怕这些表之间没有键。我期望的是——第一个查询应该按月对第二个查询返回的计数进行分组。第二个查询返回给定日期范围内所有月份的开始日期和结束日期以上是关于如何在 PostgreSQL 中合并两个查询?的主要内容,如果未能解决你的问题,请参考以下文章