BigQuery中的标准SQL-从多行获取并置文本

时间:2019-03-07 10:52:58

标签: sql google-bigquery

我有类似的表格:

文档:

+-----+---------+
| dId | score   |
+-----+---------+
| A   | 100     |
| B   | 80      |
| C   | 70      |
+-----+---------+

实体:

+------+------------+-----+
| name | details    | dId |
+------+------------+-----+
| e1   | a          |   A |
| e2   | a          |   A |
| e3   | b          |   B |
| e4   | c          |   B |
| e5   | d          |   C |
+------+------------+-----+

预期输出:

+------+--------+----------+
| dId  | score  | entities |
+------+--------+----------+
| A    | 100    |   e1, e2 |
| B    | 80     |   e3, e4 |
| C    | 70     |   e5     |
+------+--------+----------+

当前查询:

SELECT
  docT.dId,
  docT.score,
  entityT.name AS entities
FROM
  document docT,
  entity entityT
LEFT JOIN
  document_sentiment docT1
ON
  docT1.dId = entityT.dId

现在,我已经遍历了用于SQL Server的12

但是我正在寻找Standard SQL Format used by BigQuery

如何获得标准SQL格式的预期输出?

2 个答案:

答案 0 :(得分:2)

尝试如下

  select d.dId,score,STRING_AGG(e.name) 
 document d join entity e on d.did=e.did
  group by d.dId,score

答案 1 :(得分:1)

使用array_agg()-reference

SELECT
  docT.dId,
  docT.score,
  array_agg(entityT.name) AS entities
FROM
document docT join entity entityT on docT.dId=entityT.dId
LEFT JOIN document_sentiment docT1 ON docT1.dId = entityT.dId
group by docT.dId,docT.score