MySQL唯一项计数查询

时间:2017-06-12 09:00:01

标签: 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查询?谢谢你的帮助。

3 个答案:

答案 0 :(得分:0)

假设每行的customerName和customerGroup相同,请将countcountdistinct一起使用group by

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

答案 1 :(得分:0)

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

我没有在MySQL上运行它,但我认为它应该可以运行。

答案 2 :(得分:0)

您可以尝试分组此

对于taotalPurchase

Count(hasPurchase)

Count(Distinct hasPurchase)对于uniquePurchase

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