0

我有以下 3 个字段的 mysql 表:

- vouchercode: Unique KEY
- voucherstatus: 1 for unused voucher, 3 for used voucher
- partnerId

我想显示使用了多少代金券和未使用的 wrt partnerId。

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 查询。似乎我必须使用子查询和 group by 不起作用。提前致谢

4

2 回答 2

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
于 2013-05-07T04:31:59.870 回答
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;

sqlfiddle *演示*

于 2013-05-07T04:40:38.770 回答