0

I have tables like:

document:

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

entity:

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

Expected Output:

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

Current Query:

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

Now, I've gone through 1 and 2 which are for SQL-Server.

But I'm looking for Standard SQL Format used by BigQuery.

How can I get the expected output with Standard SQL format?

Mikhail Berlyant
  • 165,386
  • 8
  • 154
  • 230
user5155835
  • 4,392
  • 4
  • 53
  • 97

2 Answers2

2

try like below

  select d.dId,score,STRING_AGG(e.name) 
 document d join entity e on d.did=e.did
  group by d.dId,score
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
1

use 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
Fahmi
  • 37,315
  • 5
  • 22
  • 31