简体   繁体   English

在BigQuery / SQL中展开数组值

[英]Unwind array values in BigQuery/SQL

I was trying to unwind array values to different rows in BigQuery/ PSQL. 我试图将数组值展开为BigQuery / PSQL中的不同行。

This is what I have right now :: 这就是我现在拥有的::

Col_1                    col_2
A                      array: {1,2,3,4,5}

B                      array: {1,2,3}

C                      array: {4,5,6}

I want to convert this as shown below in BigQuery. 我想按如下BigQuery所示进行转换。

A          1
A          2
A          3
A          4
A          5
B          1
B          2
B          3
C          4
C          5
C          6

Using standard SQL (uncheck the "Use Legacy SQL" box under "Show Options") you can do: 使用标准SQL (取消选中“显示选项”下的“使用旧版SQL”框),您可以执行以下操作:

WITH MyTable AS (
  SELECT 'A' AS Col_1, [1, 2, 3, 4, 5] AS col_2
  UNION ALL SELECT 'B', [1, 2, 3]
  UNION ALL SELECT 'C', [4, 5, 6])
SELECT Col_1, col_2 FROM MyTable t, t.col_2;
+-------+-------+
| Col_1 | col_2 |
+-------+-------+
| A     |     1 |
| A     |     2 |
| A     |     3 |
| A     |     4 |
| A     |     5 |
| B     |     1 |
| B     |     2 |
| B     |     3 |
| C     |     4 |
| C     |     5 |
| C     |     6 |
+-------+-------+

Here the "comma" operator is equivalent to a cross join, which has the effect of flattening the repetition. 此处的“逗号”运算符等效于交叉连接,具有平整重复的效果。 As Pavan points out above, you can also accomplish this in legacy SQL using the FLATTEN operator, although the syntax is different. 正如Pavan指出的那样,尽管语法不同,您也可以使用FLATTEN运算符在旧版SQL中完成此操作。

If you are bound to BigQuery Legacy SQL - try below 如果您必须使用BigQuery旧版SQL,请尝试以下操作

SELECT col_1, SPLIT(REPLACE(REPLACE(SPLIT(col_2, ':'), '{', ''), '}', ''), ',') AS elem 
FROM
  (SELECT 'A' AS col_1, 'array: {1,2,3,4,5}' AS col_2),
  (SELECT 'B' AS col_1, 'array: {1,2,3}' AS col_2),
  (SELECT 'C' AS col_1, 'array: {4,5,6}' AS col_2)
HAVING elem <> 'array'  

col_1   elem     
A       1    
A       2    
A       3    
A       4    
A       5    
B       1    
B       2    
B       3    
C       4    
C       5    
C       6    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM