如何从bigquery表中获取与另一个表列的值匹配的列?

6g8kf2rb  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(367)

场景:有两个bigquery表a和b,有多列和公共键列。需要使用公共键列连接两个表,并从另一个表中获取相应的值,如下面的示例中所述。
输入:有两张table
表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',如果category在('bbb','ddd'),然后获取列'sale2',如果category='ccc',然后获取列'sale3',并将相应的值作为列'sale'存储在结果表c中。
已尝试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)

我需要帮助。提前谢谢!

ghhaqwfi

ghhaqwfi1#

你可以使用 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 表情。这个 sale= 不合适。一 case 表达式返回一个值。然后可以使用 as .

x4shl7ld

x4shl7ld2#

下面是biqquery标准sql
下面的解决方案看起来可能过于工程化,但当您希望将Map规则与代码分开时,这可能是您的首选方案,并且/或者这些规则的数量会使代码变得不可管理,等等。


# 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

相关问题