【问题标题】:How to fetch respective columns from BigQuery table with values matching from another table column joined?如何从 BigQuery 表中获取相应的列,其中的值与另一个表列相匹配?
【发布时间】:2020-11-03 14:12:16
【问题描述】:

场景: 有两个 BigQuery 表 A 和 B,有多个列和公共键列。需要使用公共键列连接两个表,并从另一个表中获取各自的值,如下面的示例所述。

输入: 有两张桌子

表 A:

store   category    city
11      aaa         xx
12      bbb         yy
12      ccc         zz
13      ddd         xy

表 B:

store   sale1   sale2   sale3
11      0.5     0.75    0.25
12      1.2     1.25    1.23
13      0.9     0.87    0.54

预期输出 - 结果表 C:

store   category    city    sale
11      aaa         xx      0.5
12      bbb         yy      1.25
12      ccc         zz      1.23
13      ddd         xy      0.87

输出解释:

第 1 点: 使用公共列“store”连接两个表

第 2 点: 检查列 category == 'aaa',然后从表 B 中获取列 'sale1',如果类别在 ('bbb','ddd'),则获取列 ' sale2' 并且如果 category == 'ccc',则获取列 'sale3' 并将相应的值存储在结果表 C 中作为列 'sale'。

尝试过 BIGQUERY:

with res as 
    (select 
    a.store,
    a.category,
    a.city
    )
SELECT store, category, city,   
    case
        when category in ('aaa') then sale=b.sale1
        when category in ('bbb','ddd') then sale=b.sale2
        when category in ('ccc') then sale=b.sale3
    end
    as sale
FROM `tableA` AS a
JOIN `tableB` AS b
ON a.store = CAST(b.store AS STRING)

需要帮助。提前致谢!

【问题讨论】:

    标签: sql join google-bigquery case


    【解决方案1】:

    您可以使用case 表达式:

    select a.store, a.category,
           (case when a.category = 'aaa' then b.sale1
                 when a.category in ('bbb', 'ddd') then b.sale2
                 when a.category in ('ccc') then b.sale3
            end) as sale
    from `tableA` a join
         `tableB` b
         on a.store = cast(b.store as string) ;
    

    其实,除了case 表达式之外,你的查询基本上是正确的(虽然CTE 是多余的)。 sale= 不合适。 case 表达式返回一个值。然后可以使用as 将其分配给列。

    【讨论】:

      【解决方案2】:

      以下是 BiQquery 标准 SQL

      以下解决方案可能看起来像是过度设计,但在您希望将映射规则与代码分开和/或此类规则的数量会使代码难以管理等情况下,这可能是您的偏好。

      #standardSQL
      WITH map AS (
        SELECT 'sale1' column, ['aaa'] categories UNION ALL
        SELECT 'sale2', ['bbb', 'ddd'] UNION ALL
        SELECT 'sale3', ['ccc']
      )
      SELECT a.*, SPLIT(kv, ':')[SAFE_OFFSET(1)] sale
      FROM `project.dataset.tableA` a
      JOIN `project.dataset.tableB` b
        ON a.store = CAST(b.store AS STRING)
      JOIN map m
        ON a.category IN UNNEST(m.categories)
      JOIN UNNEST(SPLIT(TRIM(TO_JSON_STRING(b), '{}'))) kv
        ON TRIM(SPLIT(kv, ':')[SAFE_OFFSET(0)], '"') = m.column
      

      如果将上述代码应用于您问题中的样本数据 - 输出是

      Row store   category    city    sale     
      1   11      aaa         xx      0.5  
      2   12      bbb         yy      1.25     
      3   12      ccc         zz      1.23     
      4   13      ddd         xy      0.87     
      

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 2020-09-20
        • 1970-01-01
        • 1970-01-01
        • 2020-05-18
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多