Skip to content
Advertisement

Is there a way to restrinct rolling window from summing if not 2 behind?

I want to sum over 3 rows (ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) using SQL ROLLING WINDOW:

The issue is that if try to use the statement ROWS BETWEEN 2 AND CURRENT ROW, it will provide SUM even if I have only ONE preceding row, and I would want to have result as NULL / 0 if there’s not 2 preceding and only one.

Is there a manner to have it like that?

Thank you for your time!

Advertisement

Answer

Consider below example that illustrate approach

with output

enter image description here

In case if you want at least one row behind – you would use

with output

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement