0

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!

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

@gordon-linoff, dont need to use the between, only " ROWS 3 preceding " can do the job. dbfiddle.uk/…
@Frederic . . . I am aware of that shortcut. I prefer to be explicit about window frames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.