首页 > 解决方案 > BigQuery SQL:如何从具有多个条件的一个表中的其他表中获取相应的销售额?

问题描述

有两个 Bigquery 表,

表格1:

store   article  sales
11      aa       14.5
11      bb       10.0
12      aa
12      bb
12      cc
13      aa       12.0
13      bb       11.4
13      dd       12.5

表 2:

store   status      likestore
11      Active      
12      New         13
13      New

场景: 如果该商店的 tab2.status = 'New' 并且 tab1.sales 为 NULL,则为该商店分配 tab2.likestore 的销售额。

试用:

select *,
    case when tab2.status = 'New' and tab1.sales IS NULL then <to add other conditions explained in Scenario>
    from tab1
    left join tab2 on tab2.store = tab1.store

最后结果:

store   article  sales
11      aa       14.5
11      bb       10.0
12      aa       12.0
12      bb       11.4
12      cc
13      aa       12.0
13      bb       11.4
13      dd       12.5

标签: sqlgoogle-bigquerycaseprocedure

解决方案


这回答了问题的原始版本。

嗯。. . 假设每个商店一行,然后使用left join

select t1.*,
       coalesce(t1.sales, tt1.sales) as imputed_sales
from table1 t1 left join
     table2 t2
     on t1.store = t2.store and t2.status = 'New' left join
     table1 tt1
     on tt1.store = t2.likestore;

注意:这假设这''确实意味着NULL. 对于应该是数字列的内容,空字符串没有意义。但是,如果您错误地将数字存储为字符串,则可以使用case代替coalesce().


推荐阅读