Mysql sum字段基于其他字段的值

时间:2015-08-13 11:27:45

标签: mysql

给出下表

sku     store     sold
SKU_1   store_1   22
SKU_2   store_1   10
SKU_3   store_1   15
SKU_1   store_2   10
SKU_2   store_2   50
SKU_3   store_2   10
SKU_1   store_3   1
SKU_2   store_3   4
SKU_3   store_3   61

要查询的查询是什么:

  1. 在store_1和store_2中销售了多少SKU_1
  2. 在任何超过store_1的商店中售出了多少SKU_2,即在此示例中可能是store_2和store_3,但在
  3. 中可能更多商店

2 个答案:

答案 0 :(得分:0)

SKU_1store_1

中销售了多少store_2
select sum(sold) as SKU_1_sold
from tbl
where  sku = 'SKU_1'
and store in ('store_1', 'store_2')

在任何大于SKU_2

的商店中售出了多少store_1
select sum(sold) as SKU_2_sold
from tbl
where  sku = 'SKU_2'
and store > 'store_1'

答案 1 :(得分:0)

在不同条件下进行聚合时,可以使用条件聚合作为

select
sum( 
  case 
    when sku = 'SKU_1' and store in('store_1','store_2') then sold 
    else 0 
  end
 ) as sold1,
sum( 
  case 
    when sku = 'SKU_2' and store <> 'store_1' then sold 
    else 0 
  end
) as sold2
from table_name
相关问题