窗口函数求和

时间:2019-12-13 13:42:09

标签: sql postgresql

我正在尝试通过PostgresQL的窗口函数计算总和。

INSERT INTO t VALUES
('2012-06-21 05:20:00',12),
('2012-06-21 05:21:00',14),
('2012-06-21 05:22:00',10),
('2012-06-21 05:23:00',20),
('2012-06-21 05:24:00',25),
('2012-06-21 05:25:00',30),
('2012-06-21 05:26:00',10);

SELECT dt,
cnt,
sum(cnt) OVER (order by dt ROWS BETWEEN 3 preceding AND 0 preceding)
FROM t
ORDER BY dt;

我想为每3行计数,并希望得到这样的结果,而我得到这个

2012-06-21 05:21:00 14  26
2012-06-21 05:22:00 10  36
2012-06-21 05:23:00 20  56
2012-06-21 05:24:00 25  69
2012-06-21 05:25:00 30  85
2012-06-21 05:26:00 10  85

请告诉我,有可能得到类似的结果

2012-06-21 05:20:00 12  0
2012-06-21 05:21:00 14  0
2012-06-21 05:22:00 10  36
2012-06-21 05:23:00 20  0
2012-06-21 05:24:00 25  0
2012-06-21 05:25:00 30  75
2012-06-21 05:26:00 10  0

通过窗口功能?谢谢!

1 个答案:

答案 0 :(得分:1)

只需使用条件逻辑:

SELECT dt, cnt,
       (case when row_number() over (order by dt) % 3 = 0
             then sum(cnt) OVER (order by dt ROWS BETWEEN 3 preceding AND 0 preceding)
        else 0
       end)
FROM t
ORDER BY dt;