关于case语句中sum的正确用法

vsaztqbk  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(408)

有一张“付款”表

user_id     payment_time    amount    sale_type
1            2018-04-01      10       cash
1            2018-04-01      10       cash
1            2018-04-01      10       cash
1            2018-04-01      20       bank
2            2018-04-01      10       cash
2            2018-04-01      10       cash

我需要一笔现金。
我不明白为什么这个查询会给出错误的结果:

select SUM(CASE WHEN p1.sale_type='cash' THEN p1.amount ELSE 0 END) 
as cash
FROM 
(SELECT distinct user_id, SUM(amount) AS amount, sale_type FROM payments where 
payment_time = '2018-04-01' group by user_id) p1
cdmah0mi

cdmah0mi1#

我想你可能不需要 distinct 在子查询或整个子查询中。

select p.user_id as id, sum(case when p.sale_type = 'cash' then p.amount else 0 end) as amount
from payments p 
where p.payment_time = '2018-04-01' 
group by p.user_id

或者没有 case ```
select p.user_id, sum(p.amount)
from payments p
where p.sale_type = 'cash' and p.payment_time = '2018-04-01'
group by p.user_id

5rgfhyps

5rgfhyps2#

你为什么不使用为这个目的而设的“having”子句呢。

SELECT SUM(amount) AS cash FROM payments
WHERE payment_time = '2018-04-01'
GROUP BY sale_type
HAVING sale_type= 'cash'
h9a6wy2h

h9a6wy2h3#

你需要加上 sale_type 列到 GROUP BY 内部查询的 group by user_id, sale_type 查询样式的正确结果。
p、 实际上,我认为你不需要子查询。
上面的查询给出的结果是 60 ,而

select SUM(CASE WHEN p1.sale_type='cash' THEN p1.amount ELSE 0 END) as cash
  from 
 (select distinct user_id, SUM(amount) AS amount, sale_type 
    from payments 
   where payment_time = date'2018-04-01' 
   group by user_id, sale_type) p1;

或者

select SUM(CASE WHEN sale_type='cash' THEN amount ELSE 0 END) as cash 
  from payments 
 where payment_time = date'2018-04-01'

给予 40 结果 cash
sql fiddle演示

相关问题