简体   繁体   中英

Sliding window maximum in snowflake sql

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?

在此处输入图像描述

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;

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