Google bigquery 在BigQuery中创建一个JSON列,实际列值作为键

Google bigquery 在BigQuery中创建一个JSON列,实际列值作为键,google-bigquery,Google Bigquery,有没有办法在BigQuery中创建一个以列值为键的JSON? 表中有3列: user_id (string) | category (string) | info (struct) user_1, cat_A, info_1A user_1, cat_B, info_1B user_1, cat_C, info_1C user_2, cat_A, info_2A user_3, cat_Z, info_3Z user_3, cat_B, info_3B To abbreviate the v

有没有办法在BigQuery中创建一个以列值为键的JSON?

表中有3列:

user_id (string) | category (string) | info (struct)

user_1, cat_A, info_1A
user_1, cat_B, info_1B
user_1, cat_C, info_1C
user_2, cat_A, info_2A
user_3, cat_Z, info_3Z
user_3, cat_B, info_3B

To abbreviate the values of the "info" column,
let's say that it is a struct of i.e. {'f': 2, 'c': 3, ...}

我希望有这样的输出,“features”列的键是“category”列的实际值:

但是,我目前只能实现这种格式(为了更清晰,我将输出JSON格式化),其中键是您在创建结构时给出的预定义名称,即,
STRUCT(…)作为*key*

[
  {
    "user_id": "user_1",
    "features": [
      {
        "category": "cat_A",
        "features": {
          "f": 2,
          "c": 3,
        }
      },
      {
        "category": "cat_B",
        "features": {
          "x": 7,
          "z": 10,
        }
      },
      ...
  }
  ...
]
通过使用以下查询:

选择
用户id,
数组_AGG(
结构(
类别
结构(f、c、x、z)作为特征——每个类别的不同特征
)
)
从…起
按用户id分组

下面是针对BigQuery标准SQL的

#standardSQL
SELECT user_id, '{' || STRING_AGG(category || ': ' || info, ', ') || '}' features
FROM `project.dataset.table`
GROUP BY user_id   
您可以使用问题中的样本数据测试、播放上述内容,如下例所示

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'user_1' user_id, 'cat_A' category, 'info_1A' info UNION ALL
  SELECT 'user_1', 'cat_B', 'info_1B' UNION ALL
  SELECT 'user_1', 'cat_C', 'info_1C' UNION ALL
  SELECT 'user_2', 'cat_A', 'info_2A' UNION ALL
  SELECT 'user_3', 'cat_Z', 'info_3Z' UNION ALL
  SELECT 'user_3', 'cat_B', 'info_3B' 
)
SELECT user_id, '{' || STRING_AGG(category || ': ' || info, ', ') || '}' features
FROM `project.dataset.table`
GROUP BY user_id
有输出

Row user_id features     
1   user_1  {cat_A: info_1A, cat_B: info_1B, cat_C: info_1C}     
2   user_2  {cat_A: info_2A}     
3   user_3  {cat_Z: info_3Z, cat_B: info_3B}     
Row user_id features     
1   user_1  {cat_A: info_1A, cat_B: info_1B, cat_C: info_1C}     
2   user_2  {cat_A: info_2A}     
3   user_3  {cat_Z: info_3Z, cat_B: info_3B}