有一个表格“付款”
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
答案 0 :(得分:1)
对于内部查询,您需要在sale_type
语句中添加GROUP BY
列,对于您的查询样式,正确的结果应为group by user_id, sale_type
。
P.S。实际上,我认为您不需要子查询。
上面的查询给出的结果为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
答案 1 :(得分:1)
为什么不使用为此目的而设计的“具有”子句。
SELECT SUM(amount) AS cash FROM payments
WHERE payment_time = '2018-04-01'
GROUP BY sale_type
HAVING sale_type= 'cash'
答案 2 :(得分:0)
我认为您可能根本不需要在子查询或整个子查询中使用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