我正在尝试在PostgreSQL中编写查询,该查询应在给定两个日期时按“月份”返回结果。
我希望结果是这样的(上面的查询并没有实现这个功能)。
SELECT count(overall_sl) as total_sales, count(CASE WHEN overall_sl < value_1 THEN 1 END) failed_sales
FROM (
SELECT overall_sl, value_1
FROM salecombined c where c.date_updated between '2018-01-01' and '2018-12-31'
GROUP BY dept_name, date_updated, date, overall_sl, no_addons,
value_1, category_id, subcategory_id, branch_name
) sales;
我希望结果是这样的(上面的查询并没有实现这个功能)。
start_dt end_dt total_sales failed_sales
-------- ------ ----------- -------------
2018-01-01 2018-01-31 0 0
2018-02-01 2018-02-28 589 154
2018-03-01 2018-03-31 107 14
2018-04-01 2018-04-30 375 114
-- and so on
我写了下面的查询语句,但执行时间较长;请问如何优化?
SELECT date_trunc('month', dd):: date start_dt,
(date_trunc('month', dd::DATE) + interval '1 month' - interval '1 day')::date as end_dt,
(select count(overall_sl) from (
SELECT overall_sl
FROM salecombined c
WHERE c.date_updated between date_trunc('month', dd):: date and (date_trunc('month', dd::DATE) + interval '1 month' - interval '1 day')::date
GROUP BY dept_name, date_updated, date, overall_sl, no_addons,
category_id, subcategory_id, branch_name
) jobs
) total_sales,
(select count(CASE WHEN overall_sl < value_1 THEN 1 END) from (
SELECT overall_sl, value_1
FROM salecombined c
WHERE c.date_updated between date_trunc('month', dd):: date and (date_trunc('month', dd::DATE) + interval '1 month' - interval '1 day')::date
GROUP BY dept_name, date_updated, date, overall_sl, no_addons,
value_1, category_id, subcategory_id, branch_name
) jobs
) failed_sales
FROM generate_series
( '2018-01-01'::timestamp
, '2018-12-11'::timestamp
, '1 month'::interval) dd
我不是SQL或PostgreSQL的专家。