sqlsnowflake-cloud-data-platform

Array_Agg does not support Window Frame in Snowflake - how to achieve?


I need to run:

select arrayagg(o_clerk) 
  within group (order by o_orderkey desc) 
  OVER (PARTITION BY o_orderkey order by o_orderkey 
     ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS RESULT
from sample_data

But Snowflake returns the error Sliding window frame unsupported for function ARRAYAGG. If I try to accumulate all without a sliding window, I get the error Cumulative window frame unsupported for function ARRAY_AGG.

How can I achieve this?

Sample data:

create or replace table sample_data as (
    with data as (
        select 1 a, [1,3,2,4,7,8,10] b
        union all select 2, [1,3,2,4,7,8,10]
    )

    select 'Ord'||a o_orderkey, 'c'||value o_clerk, index
    from data, table(flatten(b))
)
;

enter image description here

Desired result:

enter image description here

(source, for a BigQuery migration)


Solution

  • Thanks @Felipe Hoffa here's my solution posted initially in:

    https://community.snowflake.com/s/question/0D73r000006upCECAY/detail?fromEmail=1&s1oid=00Di0000000hZh2&s1nid=0DB3100000001Fq&s1uid=0050Z000009Xcck&s1ext=0&emkind=chatterCommentNotification&emtm=1669252526852

    select o_orderkey, 
        array_compact([
            lag(o_clerk, 3) over(partition by o_orderkey order by index)
            , lag(o_clerk, 2) over(partition by o_orderkey order by index)
            , lag(o_clerk, 1) over(partition by o_orderkey order by index)
            , o_clerk
        ])
    from sample_data

    enter image description here