在同一表格中串联BigQuery中具有相同ID的行

时间:2019-03-31 16:52:12

标签: google-bigquery

我正在Google bigquery中运行此查询

SELECT rep.key.id as id, te.cmnt as comment
FROM `table` rep, UNNEST(tre) as te
WHERE u_id LIKE 'test'
ORDER BY cts DESC

我正在得到这个

Id                    comment
---------------------------------
5165356444286976      HEloo
5165356444286976      TEST
5165356444286976

我想合并具有相同ID的所有注释,例如,看起来像这样:

Id                    comment
---------------------------------
5165356444286976      HEloo, TEST

1 个答案:

答案 0 :(得分:1)

使用STRING_AGG()

WITH table AS (
  SELECT 'test' u_id, STRUCT(1 AS id) AS key, [STRUCT('hey' AS cmnt)] AS tre, 3 cts
  UNION ALL 
  SELECT 'test', STRUCT(1), [STRUCT('you')], 2
  UNION ALL 
  SELECT 'test', STRUCT(1), [STRUCT(CAST(null AS STRING))], 1
)


SELECT rep.key.id as id, STRING_AGG(te.cmnt, ', ' ORDER BY cts DESC) AS comments
FROM `table` rep, UNNEST(tre) as te
WHERE u_id LIKE 'test'
GROUP BY id