在 BigQuery 中使用双数组取消嵌套结构
Unnest STRUCT with double array in BigQuery
我正在尝试找到一种方法来共享一些示例数据(下面的 'Some_Data'),以便在共享 SQL 片段时演示功能。
我知道我可以用一系列 UNION ALL 语句来做到这一点,但我想减少行数(这在这个例子中并不重要,但假设我们有 20 多行)。
我想我可以使用数组和结构来做到这一点,我已经设法让它工作了,但是代码看起来真的很乱,我希望有人可以建议我如何简化它?
WITH
Some_Data AS (
SELECT
[STRUCT
(
["a", "b"] AS letters,
[1, 2] AS numbers
)
] AS Data_Sample
)
SELECT t_numbers, t_letters FROM
((
SELECT letters, numbers
FROM Some_Data s
CROSS JOIN UNNEST(s.Data_Sample)
)) t
CROSS JOIN UNNEST(t.numbers) as t_numbers WITH OFFSET nm
LEFT JOIN UNNEST(t.letters) as t_letters WITH OFFSET lt
ON nm = lt
输出(如预期):
Row
t_numbers
t_letters
1
1
a
2
2
b
I was hoping someone could suggest how I could simplify this?
考虑以下方法(在我看来更简单、更简洁)
select number, letter
from Some_Data t, t.Data_Sample el,
el.letters letter with offset
join el.numbers number with offset
using(offset)
如果应用于您问题中的示例数据 - 输出为
我正在尝试找到一种方法来共享一些示例数据(下面的 'Some_Data'),以便在共享 SQL 片段时演示功能。
我知道我可以用一系列 UNION ALL 语句来做到这一点,但我想减少行数(这在这个例子中并不重要,但假设我们有 20 多行)。
我想我可以使用数组和结构来做到这一点,我已经设法让它工作了,但是代码看起来真的很乱,我希望有人可以建议我如何简化它?
WITH
Some_Data AS (
SELECT
[STRUCT
(
["a", "b"] AS letters,
[1, 2] AS numbers
)
] AS Data_Sample
)
SELECT t_numbers, t_letters FROM
((
SELECT letters, numbers
FROM Some_Data s
CROSS JOIN UNNEST(s.Data_Sample)
)) t
CROSS JOIN UNNEST(t.numbers) as t_numbers WITH OFFSET nm
LEFT JOIN UNNEST(t.letters) as t_letters WITH OFFSET lt
ON nm = lt
输出(如预期):
Row | t_numbers | t_letters |
---|---|---|
1 | 1 | a |
2 | 2 | b |
I was hoping someone could suggest how I could simplify this?
考虑以下方法(在我看来更简单、更简洁)
select number, letter
from Some_Data t, t.Data_Sample el,
el.letters letter with offset
join el.numbers number with offset
using(offset)
如果应用于您问题中的示例数据 - 输出为