如何在大查询中转动

时间:2017-12-12 14:11:50

标签: google-bigquery

说我有数据

ID,COL1,COL2,COL3,COL4,COL5

1,A,B,C,d,E

我希望结果是......

1,

1,B

1,C

1,d

1,E

如何在大查询中转向id?

1 个答案:

答案 0 :(得分:1)

以下是BigQuery Standard SQL

  
#standardSQL
CREATE TEMP FUNCTION cols_to_rows(root STRING) AS (
  ARRAY(SELECT REPLACE(SPLIT(kv, ':') [OFFSET(1)], '"', '') cols 
  FROM UNNEST(SPLIT(REGEXP_REPLACE(root, r'^{|}$', ''))) kv
  WHERE SPLIT(kv, ':') [OFFSET(0)] != '"id"'
  )
);
SELECT id, col
FROM `project.dataset.table` t,
UNNEST(cols_to_rows(TO_JSON_STRING(t))) col  

您可以使用以下虚拟数据进行上述测试/播放

#standardSQL
CREATE TEMP FUNCTION cols_to_rows(root STRING) AS (
  ARRAY(SELECT REPLACE(SPLIT(kv, ':') [OFFSET(1)], '"', '') cols 
  FROM UNNEST(SPLIT(REGEXP_REPLACE(root, r'^{|}$', ''))) kv
  WHERE SPLIT(kv, ':') [OFFSET(0)] != '"id"'
  )
);
WITH `project.dataset.table` AS (
  SELECT 1 id, 'a' col1, 'b' col2, 'c' col3, 'd' col4, 'e' col5 UNION ALL
  SELECT 2 id, 'x', 'y', 'z', 'v', 'w' 
)
SELECT id, col
FROM `project.dataset.table` t,
UNNEST(cols_to_rows(TO_JSON_STRING(t))) col  

结果为

id  col  
1   a    
1   b    
1   c    
1   d    
1   e    
2   x    
2   y    
2   z    
2   v    
2   w