2017-06-12 88 views
0

我有這個表上的MySQL。MySQL獨特的項目數量查詢

CustomerName CustomerGroup hasPurchase 
Jerry  A    CAR 
Jerry  A    TOY 
Jerry  A    CAR 
Springer  B    DRINK 
Springer  B    CAR 
Springer  B    CAR 
Springer  B    DRINK 

我的預期結果:

CustomerName CustomerGroup totalPurchase uniquePurchase 
Jerry  A    3    2 
Springer  B    4    2 

totalPurchase是他買的全部項目。 uniquePurchase是他購買的不同類型的物品。

這是什麼是正確的MySQL查詢? Thx尋求幫助。

+0

你嘗試過什麼到目前爲止? – Faisal

+0

顯示您的試用代碼。 – user1234

回答

0
SELECT DISTINCT CustomerName, 
       CustomerGroup, 
       COUNT(hasPurchase) as totalPurchase, 
       COUNT(DISTINCT hasPurchase) as uniquePurchase 
FROM XXX 
GROUP BY CustomerName, 
     CustomerGroup 

我沒有在MySQL運行它一起,但我認爲它應該工作。

+1

thx,它正在工作。 –

0

假設客戶名稱和customerGroup是相同的每一行,使用countcountdistinctgroup by

select customerName 
,customerGroup 
,count(hasPurchase) as totalPurchase 
,count(distinct hasPurchase) as uniquePurchase 
from your_table 
group by CustomerName,CustomerGroup 
0

您可以通過此

Count(hasPurchase)嘗試組taotalPurchase

Count(Distinct hasPurchase)爲uniquePurchase

SELECT customerName,customerGroup,count(hasPurchase) as totalPurchase,count(distinct hasPurchase) as uniquePurchase 
from table group by CustomerName;