group by搞砸我的计数mysql

时间:2018-04-05 18:28:34

标签: mysql if-statement group-by

我有一张基本表:

id  client  trans_date  returned
1    bob    20180301       0
2    frank  20180301       0
3    bob    20180401       1

id喜欢获得客户分组​​的结果,并计算购买的商品数量和退货数量。喜欢这个

name  bought returned
bob    1       1
frank  1       0

我尝试了这个,但它没有工作

SELECT 
     soldto AS name,
     IF(return=0,count(id),'0') AS bought,
     IF(return=1,count(id),'0') AS returned 
FROM sales 
WHERE sdate BETWEEN '20180201000000' AND '20180501000000'
group by soldto;

1 个答案:

答案 0 :(得分:0)

使用条件聚合

SELECT 
     soldto AS name,
     COUNT(*) AS bought,
     -- or maybe COUNT( CASE WHEN return = 0 THEN 1 END) AS bought,
     COUNT( CASE WHEN return = 1 THEN 1 END) AS returned 
FROM sales 
WHERE sdate BETWEEN '20180201000000' AND '20180501000000'
GROUP BY soldto;