[英]Summing column that is grouped - SQL
我有一個查詢:
SELECT
date,
COUNT(o.row_number)FILTER (WHERE o.row_number > 1 AND date_ddr IS NOT NULL AND telephone_number <> 'Anonymous' ) repeat_calls_24h
(
SELECT
telephone_number,
date_ddr,
ROW_NUMBER() OVER(PARTITION BY ddr.telephone_number ORDER BY ddr.date) row_number,
FROM
table_a
)o
GROUP BY 1
生成下表:
日期 | 重復呼叫_24h |
---|---|
2022 年 9 月 17 日 | 182 |
2022 年 9 月 18 日 | 381 |
2022 年 9 月 19 日 | 81 |
2022 年 9 月 20 日 | 24 |
21/09/2022 | 91 |
22/09/2022 | 110 |
23/09/2022 | 231 |
我可以在查詢中添加什么以提供前三天的總和,如下所示?:
日期 | 重復呼叫_24h | 重復呼叫 3d |
---|---|---|
2022 年 9 月 17 日 | 182 | |
2022 年 9 月 18 日 | 381 | |
2022 年 9 月 19 日 | 81 | 644 |
2022 年 9 月 20 日 | 24 | 486 |
21/09/2022 | 91 | 196 |
22/09/2022 | 110 | 225 |
23/09/2022 | 231 | 432 |
謝謝
我們可以使用lag
來做到這一點。
select "date"
,"Repeat calls_24h"
,"Repeat calls_24h" + lag("Repeat calls_24h") over(order by "date") + lag("Repeat calls_24h", 2) over(order by "date") as "Repeat Calls 3d"
from t
日期 | 重復呼叫_24h | 重復呼叫 3d |
---|---|---|
2022-09-17 | 182 | null |
2022-09-18 | 381 | null |
2022-09-19 | 81 | 644 |
2022-09-20 | 24 | 486 |
2022-09-21 | 91 | 196 |
2022-09-22 | 110 | 225 |
2022-09-23 | 231 | 432 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.