简体   繁体   中英

Is there a way to use a declared variable in BigQuery SQL with ROWS BETWEEN 'variable' PRECEDING AND CURRENT ROW in a window function?

Currently getting the error "Window framing expression must be a literal or parameter at [x:x]", it works fine using just the number 5 but this is used a lot throughout my script.

DECLARE variable INT64;
SET variable = 5;

SELECT col1, value, time, 
                CASE
                    WHEN "Bla" = "Bla"
                    THEN MIN(value) OVER (PARTITION BY col1 ORDER BY time ROWS BETWEEN variable PRECEDING AND CURRENT ROW) 
                    ELSE NULL
                    END 
                AS MinVal

FROM data

You can use execute immediate to execute dynamic queries. For eg. Below query uses var in over clause.

EXECUTE IMMEDIATE

declare var int64 default 5;

execute immediate

'select min(1) over(order by street_number ROWS BETWEEN '||var||' PRECEDING AND CURRENT ROW) from' ||'`bigquery-public-data.austin_311.311_service_requests` limit 100' 

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