BigQuery - 将多行连接成一行

时间:2017-02-02 08:04:19

标签: google-bigquery

我有一个包含2列的BigQuery表:

id|name
1|John
1|Tom
1|Bob
2|Jack
2|Tim

预期输出:按ID分组的连接名称

id|Text
1|John,Tom,Bob
2|Jack,Tim

2 个答案:

答案 0 :(得分:10)

对于BigQuery Standard SQL:

#standardSQL
--WITH yourTable AS (
--  SELECT 1 AS id, 'John' AS name UNION ALL
--  SELECT 1, 'Tom' UNION ALL
--  SELECT 1, 'Bob' UNION ALL
--  SELECT 2, 'Jack' UNION ALL
--  SELECT 2, 'Tim' 
--)
SELECT 
  id, 
  STRING_AGG(name ORDER BY name) AS Text 
FROM yourTable 
GROUP BY id

ORDER BY name中的STRING_CONCAT选项允许您输出已排序的名单列表,如下所示

id  Text     
1   Bob,John,Tom     
2   Jack,Tim     

对于旧版SQL

#legacySQL
SELECT 
  id, 
  GROUP_CONCAT(name) AS Text   
FROM yourTable
GROUP BY id  

如果你需要在这里输出排序列表,你可以在下面使用(正式 - BigQuery Legacy SQL无法保证获得排序列表 - 但对于大多数实际情况我都有 - 它有效)

#legacySQL
SELECT 
  id, 
  GROUP_CONCAT(name) AS Text 
FROM (
  SELECT id, name 
  FROM yourTable 
  ORDER BY name
)
GROUP BY id  

答案 1 :(得分:1)

您可以使用GROUP_CONCAT

SELECT id, GROUP_CONCAT(name) AS Text FROM <dataset>.<table> GROUP BY name