从BigQuery返回汇总的JSON?

时间:2019-03-18 16:21:22

标签: sql google-bigquery

如果我在BigQuery中使用以下example_table。当我使用“原始查询”查询表时,会得到“实际结果”(从此开始)。是否可以直接查询BigQuery以获得“所需结果”

原始查询

SELECT ID, SUBID FROM `example_table ORDER BY ID

example_table

ID | SUBID
12   abc
12   def
12   ghi
34   jkl
34   mno
56   prg

实际结果

[{
    "ID": "12",
    "SUBID": "abc"
}, {
    "ID": "12",
    "SUBID": "def"
}, {
    "ID": "12",
    "SUBID": "ghi"
}, {
    "ID": "34",
    "SUBID": "jkl"
}, {
    "ID": "34",
    "SUBID": "mno"
}, {
        "ID": "56",
        "SUBID": "prg"
    }]

所需结果

[{
    "ID": "12",
    "SUBID": ["abc", "def", "ghi"]
}, {
    "ID": "34",
    "SUBID": ["jkl", "mno"]
}, {
        "ID": "56",
        "SUBID": ["prg"]
    }]

2 个答案:

答案 0 :(得分:3)

以下是用于BigQuery标准SQL

#standardSQL
SELECT ID, ARRAY_AGG(SUBID) SUBID
FROM `project.dataset.example_table`
GROUP BY ID

您可以使用问题中的示例数据来测试,玩游戏,如下例所示

#standardSQL
WITH `project.dataset.example_table` AS (
  SELECT 12 ID, 'abc' SUBID UNION ALL
  SELECT 12, 'def' UNION ALL
  SELECT 12, 'ghi' UNION ALL
  SELECT 34, 'jkl' UNION ALL
  SELECT 34, 'mno' UNION ALL
  SELECT 56, 'prg' 
)
SELECT ID, ARRAY_AGG(SUBID) SUBID
FROM `project.dataset.example_table`
GROUP BY ID
-- ORDER BY ID

有结果

enter image description here

答案 1 :(得分:1)

如果BigQuery确实使用MySQL语法,则可以执行此操作。如果不是这样,您可以使用多个选择在整个查询中继续执行CONCAT,但是要比JSON_ARRAYAGG复杂得多。

SELECT CONCAT('{','ID:', ID,', SUBID:', JSON_ARRAYAGG(SUBID),'}') as JSON
FROM contact GROUP BY ID;

https://www.db-fiddle.com/f/37ru5oq4dFQSscwYsfx386/25