我想在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中编写此查询?
答案 0 :(得分:0)
您可以尝试以下操作
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