计数基于 store_A 和所有商店

count based on store_A and all stores

我要数:

Main_table

date         store_id  count_prroducts
2019-01-01   A         13
2019-01-01   B         34
2019-01-01   C         63
2019-01-01   D         10

Output_table

date          store_A_count_products    total_count_products
2019-01-0     13                        120 

首先选择不做任何修改的日期列。

对于store_A_count_products,基本上你需要做的就是只要store_id是A就把所有的count_products加起来。你可以用一个case语句来做到这一点:

   case when store_id = 'A' then count_products else 0 end

这基本上是一种 IF/ELSE 情况,对于 store_id 列中没有 A 的任何行,return 都将为 0。

如果将其包装在 SUM() 中,您会将所有行加在一起。

对于 total_count_products,您只需将 SUM() 包裹在 count_products 周围。这将添加所有行,而不管任何其他列的状态。

最后,您需要按日期列进行分组。分组依据是一种将聚合数据拆分到未聚合列的方法。

之所以可行,是因为它为每个日期提供一行,即商店 A 的产品总计和所有产品的总计。

Select 
    date,
    Sum(case when store_id = 'A' then count_products else 0 end) as store_A_count_products,
    SUM(count_products) as total_count_products
From main_table
Group by date;