mysql leetcode 1445. 苹果和桔子 分组求差值

这道题的难点在于求差值,因为这道题比较特殊

假设只有这两种水果

select
sale_date,
sum(if(fruit='apples', 1, -1)*sold_num) as diff
from `Sales`
group by sale_date
order by sale_date

sum函数与if结合,相差即减法,一个为负数,所以可以if(condition,1-1)*column

但一般情况不止是两种水果

select
sale_date,
sum(
    case fruit
    when 'apples'
    then 1
    when 'oranges'
    then -1
    end
    *sold_num
) as diff
from `Sales`
group by sale_date
order by sale_date
原文地址:https://www.cnblogs.com/littlebob/p/13500291.html