我有以下3个字段的mysql表:
- vouchercode: Unique KEY
- voucherstatus: 1 for unused voucher, 3 for used voucher
- partnerId
我想显示使用和未使用的优惠券数量。\ n伙伴ID
Example :- table data
PartnerId voucherstaus vouchercode(unique)
1 1
1 3
1 1
2 3
2 3
2 1
Result:
PartnerId usedvouchers unusedvouchers
1 1 2
2 2 1
请帮我解决mysql查询问题。似乎我必须使用子查询和分组不起作用。提前致谢
答案 0 :(得分:3)
SELECT partnerID,
SUM(CASE WHEN voucherstatus = 1 THEN 1 ELSE 0 END) unusedvouchers,
SUM(CASE WHEN voucherstatus = 3 THEN 1 ELSE 0 END) usedvouchers
FROM data
GROUP BY partnerID
答案 1 :(得分:0)
select PartnerId, SUM(case when voucher_status =1 then 1 else 0 end) as unused, sum(case when voucher_status =3 then 1 else 0 end) as used from Voucher group by PartnerID;