如何在多个查询中重复使用枢轴值列表?
给定以下最小示例:
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'))
我想拥有季度
值的列表(('q1','q2','q3','q4',q4')
)不是直接在查询本身中,而是在我的脚本顶部以某种方式,因为(在实际脚本中)我在多个位置使用它,并且不想每次复制它。除了我明确更改应用程序的整个业务逻辑之外,列表不会更改,因此我不需要“变量”即可变形(“ Dynamic Pivot”),我只想不复制列表(保持干燥),以防万一我需要更改它,我只需要在一个地方更改它即可。
我目前的尝试如下:
DECLARE quarters ARRAY <STRING> DEFAULT ['Q1', 'Q2', 'Q3', 'Q4'];
SELECT * FROM
Produce
PIVOT(SUM(sales) FOR quarter IN UNNEST(quarters))
但是它不起作用(语法错误:意外”)
)。我该如何正确执行?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我的理解,不支持使用数组作为枢轴列。但是在动态SQL中,您可以利用一个数组来生成枢轴列,如下所示。
As per my understanding, using an array as pivot columns is not supported. But in dynamic sql, you can utilize an array to generate pivot columns like below.