简体   繁体   中英

Sum by window function

I`m trying to count sum by window function of 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;

I want to count for each 3 rows and expect to get such a result and i get this

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

Tell me, please, it is possible to get result like

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

by window function? Thanks!

Just use conditional logic:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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