【问题标题】:Create a JSON column in BigQuery with the actual column values as keys在 BigQuery 中使用实际列值作为键创建 JSON 列
【发布时间】:2020-03-30 15:27:03
【问题描述】:

有没有办法在 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, ...}

我想要这个输出,其中“特征”列的是“类别”列的实际值:

user_id (string) | features (struct/JSON)
user_1, {cat_A: info_1A, cat_B: info_1B, cat_C: info_1C, ...}
user_2, {cat_A: info_2A}
user_3, {cat_Z: info_3Z, cat_B: info_3B}

但是,我目前只能实现这种格式(为了更清楚,我将输出设置为 JSON 格式),其中 keys 是您在创建STRUCT 即STRUCT(...) AS *key*:

[
  {
    "user_id": "user_1",
    "features": [
      {
        "category": "cat_A",
        "features": {
          "f": 2,
          "c": 3,
        }
      },
      {
        "category": "cat_B",
        "features": {
          "x": 7,
          "z": 10,
        }
      },
      ...
  }
  ...
]

通过使用以下查询:

SELECT
  user_id,
  ARRAY_AGG(
    STRUCT(
      category,
      STRUCT(f, c, x, z) AS features -- the different features for each category
    )
  )
FROM ...
GROUP BY user_id

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    以下是 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}     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-05
      • 2023-04-06
      • 2020-03-19
      • 2019-03-16
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多