鉴于我有一个名为orders
订单
id
customer_id
created_at
如何编写查询以返回每位客户的每月累计订单数量?我希望将2018年1月至2018年5月系列中缺少的月份包括在内。
数据
id customer_id created_at
1 200 01/20/2018
2 300 01/21/2018
3 200 01/22/2018
4 200 03/20/2018
5 300 03/20/2018
6 200 04/20/2018
7 200 04/20/2018
预期结果
customer_id month count
200 01/01/2018 2
200 02/01/2018 2
200 03/01/2018 3
200 04/01/2018 5
200 05/01/2018 5
300 01/01/2018 1
300 02/01/2018 1
300 03/01/2018 2
300 04/01/2018 2
300 05/01/2018 2
我有一个查询来计算每月的净累计数。在将查询转换为按客户累积计数工作时,我没有取得多大成功。
WITH monthly_orders AS (
SELECT date_trunc('month', orders.created_at) AS mon,
COUNT(orders.id) AS mon_count
from orders
GROUP BY 1
)
SELECT TO_CHAR(mon, 'YYYY-MM') AS mon_text,
COALESCE(SUM(c.mon_count) OVER (ORDER BY c.mon), 0) AS running_count
FROM generate_series('2018-01-01'::date, '2018-06-01'::date, interval '1 month') mon
LEFT JOIN monthly_orders c USING(mon)
ORDER BY mon_text;
答案 0 :(得分:1)
如果我理解正确,你可以这样做:
select o.customer_id, date_trunc('month', o.created_at) AS mon,
count(*) AS mon_count,
sum(count(*)) over (partition by o.customer_id
order by date_trunc('month', o.created_at)
) as running_count
from orders o
group by o.customer_id, mon
order by o.customer_id, mon;