我有一张桌子:
user device minutes
==== ====== =======
ben phone 1.9
ben tablet 2.3
anna phone 1.6
我希望用户将设备的使用打包成json字符串,如:
user json
==== =====
ben {"phone":1.9, "tablet":2.3}
anna {"phone":1.6, "tablet":2.3}
我怎么能在bigquery中做到这一点?
答案 0 :(得分:4)
以下是BigQuery Standard SQL的版本
#standardSQL
WITH `yourproject.yourdataset.yourtable` AS (
SELECT 'ben' user, 'phone' device, 1.9 minutes UNION ALL
SELECT 'ben', 'tablet', 2.3 UNION ALL
SELECT 'anna', 'phone', 1.6
)
SELECT
user,
CONCAT('{', STRING_AGG(CONCAT('"',device, '":', CAST(minutes AS STRING))), '}') json,
ROUND(SUM(IF(device='tablet',minutes,0)),2) tablet_minutes
FROM `yourproject.yourdataset.yourtable`
GROUP BY user
输出如下
user json tablet_minutes
ben {"phone":1.9,"tablet":2.3} 2.3
anna {"phone":1.6} 0.0
答案 1 :(得分:0)
使用BigQuery Legacy SQL
# legacySQL
SELECT
user,
json,
JSON_EXTRACT_SCALAR(json, '$.tablet') AS tablet_minutes
FROM (
SELECT
user,
CONCAT('{', GROUP_CONCAT_UNQUOTED(CONCAT('"', device,'":', minutes)), '}') AS json,
FROM
(SELECT 'ben' user, 'phone' device, '1.9' minutes),
(SELECT 'ben' user, 'tablet' device, '2.3' minutes),
(SELECT 'anna' user, 'phone' device, '1.6' minutes),
GROUP BY
user)
使用标准SQL(感谢Mikhail)
# standardSQL
WITH `yourproject.yourdataset.yourtable` AS (
SELECT 'ben' user, 'phone' device, 1.9 minutes UNION ALL
SELECT 'ben', 'tablet', 2.3 UNION ALL
SELECT 'anna', 'phone', 1.6
)
SELECT
user,
CONCAT('{', STRING_AGG(CONCAT('"',device, '":', CAST(minutes AS STRING))), '}') json,
ROUND(SUM(IF(device='tablet',minutes,0)),2) tablet_minutes
FROM `yourproject.yourdataset.yourtable`
GROUP BY user
两个输出
user json tablet_minutes
==== ==== ==============
ben {"phone":1.9,"tablet":2.3} 2.3
anna {"phone":1.6} 0.0