Given the following minimal example:
CREATE OR REPLACE TEMP TABLE Produce AS (
SELECT 'Kale' as product, 51 as sales, 'Q1' as quarter, 2020 as year UNION ALL
SELECT 'Kale', 23, 'Q2', 2020 UNION ALL
SELECT 'Kale', 45, 'Q3', 2020 UNION ALL
SELECT 'Kale', 3, 'Q4', 2020 UNION ALL
SELECT 'Kale', 70, 'Q1', 2021 UNION ALL
SELECT 'Kale', 85, 'Q2', 2021 UNION ALL
SELECT 'Apple', 77, 'Q1', 2020 UNION ALL
SELECT 'Apple', 0, 'Q2', 2020 UNION ALL
SELECT 'Apple', 1, 'Q1', 2021);
SELECT * FROM
Produce
PIVOT(SUM(sales) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4'))
I'd like to have the list of quarter
values (('Q1', 'Q2', 'Q3', 'Q4')
) not directly in the query itself, but somehow at the top of my script, because (in my actual script) I'm using it in multiple places and don't want to duplicate it every time. The list will not change in my case, except I explicitly change the whole business logic of the app, so I don't need the "variable" to be mutable ("dynamic pivot"), I just want to not duplicate the list (keep things DRY), so that in case I need to change it, I only need to change it in one place.
My current attempt looks as follows:
DECLARE quarters ARRAY <STRING> DEFAULT ['Q1', 'Q2', 'Q3', 'Q4'];
SELECT * FROM
Produce
PIVOT(SUM(sales) FOR quarter IN UNNEST(quarters))
But it does not work (Syntax error: Unexpected ")"
). How do I do it correctly?