假设我得到一个临时表,其中一个字段是一个数组,如何将其转换为多行?
使用PostgreSQL,可以使用UNNEST http://sqlfiddle.com/#!15/21673/19
来完成WITH x AS (SELECT ARRAY[1,3,2] AS arr)
SELECT UNNEST(arr) FROM x
在BigQuery中运行相同的查询说语法错误:意外 关键字UNNEST在[3:8]
似乎在BigQuery中,UNNEST只能放在FROM子句之后,
然后我尝试了这些:
WITH x AS (SELECT ARRAY[1,3,2] AS arr)
SELECT * FROM UNNEST(x)
这个说 UNNEST不适用于桌子:x在[3:22] ;或者这个
WITH x AS (SELECT ARRAY[1,3,2] AS row)
SELECT * FROM UNNEST(x.arr)
说 UNNEST不适用于桌子:x.arr at [3:22]
BTW,当前临时表x如下所示:
WITH x AS (SELECT ARRAY[1,2] AS row)
SELECT * FROM x
EOF
+--------------+
| row |
+--------------+
| [u'1', u'2'] |
+--------------+
虽然我希望把它变成有价值的行:
+-----+
| row |
+-----+
| 1 |
| 2 |
+-----+
答案 0 :(得分:11)
又一个版本 - 涉及“明确的”UNNEST
WITH x AS (SELECT ARRAY[1,3,2] AS arr)
SELECT arr_item FROM x, UNNEST(arr) as arr_item
答案 1 :(得分:6)
你可以通过对x的每一行进行arr元素的CROSS JOIN来进行这种展平,即
WITH x AS (SELECT ARRAY[1,3,2] AS arr)
SELECT arr FROM x, x.arr
或者您可以更明确地将其编写为CROSS JOIN,而不是使用逗号
WITH x AS (SELECT ARRAY[1,3,2] AS arr)
SELECT arr FROM x CROSS JOIN x.arr
答案 2 :(得分:0)
如果你想按数组创建普通表,你可以在FROM语句中使用UNNEST。
WITH x AS (
SELECT
*
FROM
UNNEST([1,2,3]) as num
)
select * from x