[英]Summing column that is grouped - SQL
I have a query:我有一个查询:
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
Generating the following table:生成下表:
date![]() |
Repeat calls_24h![]() |
---|---|
17/09/2022 ![]() |
182 ![]() |
18/09/2022 ![]() |
381 ![]() |
19/09/2022 ![]() |
81 ![]() |
20/09/2022 ![]() |
24 ![]() |
21/09/2022 ![]() |
91 ![]() |
22/09/2022 ![]() |
110 ![]() |
23/09/2022 ![]() |
231 ![]() |
What can I add to my query to provide a sum of the previous three days as below?:我可以在查询中添加什么以提供前三天的总和,如下所示?:
date![]() |
Repeat calls_24h![]() |
Repeat Calls 3d![]() |
---|---|---|
17/09/2022 ![]() |
182 ![]() |
|
18/09/2022 ![]() |
381 ![]() |
|
19/09/2022 ![]() |
81 ![]() |
644 ![]() |
20/09/2022 ![]() |
24 ![]() |
486 ![]() |
21/09/2022 ![]() |
91 ![]() |
196 ![]() |
22/09/2022 ![]() |
110 ![]() |
225 ![]() |
23/09/2022 ![]() |
231 ![]() |
432 ![]() |
Thanks谢谢
We can do it using lag
.我们可以使用
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
date![]() |
Repeat calls_24h![]() |
Repeat Calls 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.