Reputation: 711
If I have the below example_table
in BigQuery. When I query the table with "Original Query" I get the "Actual Result" (which makes since). Is there a way to query BigQuery directly to get the "Desired Result"
SELECT ID, SUBID FROM `example_table ORDER BY ID
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"]
}]
Upvotes: 1
Views: 5604
Reputation: 173028
Below is for BigQuery Standard SQL
#standardSQL
SELECT ID, ARRAY_AGG(SUBID) SUBID
FROM `project.dataset.example_table`
GROUP BY ID
You can test, play with above using sample data from your question as in example below
#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
with result
Upvotes: 5
Reputation: 195
If BigQuery does use MySQL syntax you might be able to do this. If not you can continue CONCAT throughout all of your query using multiple selects but it would be a little more convoluted instead of the 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
Upvotes: 0