Home > Software design >  Sliding window maximum in snowflake sql
Sliding window maximum in snowflake sql

Time:09-27

I need to find the sliding window maximum of date column in Snowflake. Window size here is 2, and maximum is stored in a new column. This is my code.

WITH temp AS(
  SELECT DISTINCT L_SHIPDATE
  FROM my_table
)

SELECT L_SHIPDATE, MAX(L_SHIPDATE) OVER (ORDER BY 'Row' ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS MAX_L_SHIPDATE
FROM temp

Below is my output. It is wrong. In Row 1, MAX_L_SHIPDATE must be max L_SHIPDATE of Rows 1 and 2, which is 1997-08-04, and row 2, must be max(L_SHIPDATE) of rows 2 and 3 which is 1998-01-03 and so on. How to fix this ?

enter image description here

CodePudding user response:

You are ordering by 'Row' - which makes no particular order. I included the row_number to order by row numbers:

with select temp AS(
  SELECT DISTINCT L_SHIPDATE
  FROM my_table
),
temp_with_rn as (
  select row_number() OVER (ORDER BY 1) rn, L_SHIPDATE 
  FROM temp
)
SELECT L_SHIPDATE, MAX(L_SHIPDATE) OVER (ORDER BY rn ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS MAX_L_SHIPDATE
FROM temp_with_rn
ORDER BY rn;

Or maybe you want to order by L_SHIPDATE:

with temp as (
  SELECT DISTINCT L_SHIPDATE
  FROM my_table
)
SELECT L_SHIPDATE, MAX(L_SHIPDATE) OVER (ORDER BY L_SHIPDATE ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS MAX_L_SHIPDATE
FROM temp
ORDER BY L_SHIPDATE;
  • Related