2017-06-12 75 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;