我有下表,需要查找每个客户发送的电子邮件的 3 个月滚动总数。
客户 ID | eom_日期 | 电子邮件_已发送 |
---|---|---|
1 | 2023-06-30 | 2 |
1 | 2023-05-31 | 空 |
1 | 2023-04-30 | 3 |
1 | 2023-03-31 | 2 |
1 | 2023-02-28 | 空 |
1 | 2023-01-31 | 空 |
2 | 2023-06-30 | 1 |
2 | 2023-05-31 | 1 |
2 | 2023-04-30 | 4 |
2 | 2023-03-31 | 空 |
2 | 2023-02-28 | 2 |
2 | 2023-01-31 | 3 |
2 | 2022-12-31 | 1 |
这是期望的结果:
客户 ID | eom_日期 | 电子邮件_已发送 | total_email_3month |
---|---|---|---|
1 | 2023-06-30 | 2 | 5 |
1 | 2023-05-31 | 空 | 5 |
1 | 2023-04-30 | 3 | 5 |
1 | 2023-03-31 | 2 | 2 |
1 | 2023-02-28 | 空 | 0 |
1 | 2023-01-31 | 空 | 0 |
2 | 2023-06-30 | 1 | 6 |
2 | 2023-05-31 | 1 | 5 |
2 | 2023-04-30 | 4 | 6 |
2 | 2023-03-31 | 空 | 5 |
2 | 2023-02-28 | 2 | 6 |
2 | 2023-01-31 | 3 | 4 |
2 | 2022-12-31 | 1 | 1 |
例如,客户 1 在“2023-06-30”应收到总共 5 封电子邮件(2 + null + 3)。
我尝试在查询中使用分区和范围,但我不完全理解窗口函数:
SELECT cust_id,
eom_date,
SUM(email_sent),
SUM(email_sent) OVER (cust_id ORDER BY time_eom_date RANGE BETWEEN 3 PRECEDING AND CURRENT ROW) total_email_3month
FROM my_table
GROUP BY 1, 2
您想要总和:
SUM(SUM(email_sent)) OVER (...)
。
SELECT
cust_id,
eom_date,
SUM(email_sent),
SUM(SUM(email_sent)) OVER (PARTITION BY cust_id
ORDER BY eom_date
RANGE BETWEEN 3 PRECEDING
AND CURRENT ROW) AS total_email_3month
FROM my_table
GROUP BY cust_id, eom_date
ORDER BY cust_id, eom_date;