我有一张基本表:
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;
答案 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;