简体   繁体   English

分组的求和列 - SQL

[英]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重复呼叫_24h
17/09/2022 2022 年 9 月 17 日 182 182
18/09/2022 2022 年 9 月 18 日 381 381
19/09/2022 2022 年 9 月 19 日 81 81
20/09/2022 2022 年 9 月 20 日 24 24
21/09/2022 21/09/2022 91 91
22/09/2022 22/09/2022 110 110
23/09/2022 23/09/2022 231 231

What can I add to my query to provide a sum of the previous three days as below?:我可以在查询中添加什么以提供前三天的总和,如下所示?:

date日期 Repeat calls_24h重复呼叫_24h Repeat Calls 3d重复呼叫 3d
17/09/2022 2022 年 9 月 17 日 182 182
18/09/2022 2022 年 9 月 18 日 381 381
19/09/2022 2022 年 9 月 19 日 81 81 644 644
20/09/2022 2022 年 9 月 20 日 24 24 486 486
21/09/2022 21/09/2022 91 91 196 196
22/09/2022 22/09/2022 110 110 225 225
23/09/2022 23/09/2022 231 231 432 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重复呼叫_24h Repeat Calls 3d重复呼叫 3d
2022-09-17 2022-09-17 182 182 null null
2022-09-18 2022-09-18 381 381 null null
2022-09-19 2022-09-19 81 81 644 644
2022-09-20 2022-09-20 24 24 486 486
2022-09-21 2022-09-21 91 91 196 196
2022-09-22 2022-09-22 110 110 225 225
2022-09-23 2022-09-23 231 231 432 432

Fiddle小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM