2013-05-07 109 views
0

我有mysql表以下三個領域:尋找MySQL查詢

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

我想顯示多少代金券使用和未使用w.r.t 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不起作用。在此先感謝

+0

你爲什麼要使用SQL服務器的標籤呢? – hd1 2013-05-07 04:30:34

回答

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 
+0

非常感謝。這個對我有用 。 – 2013-05-07 05:16:28

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 *demo*