簡體   English   中英

MySQL唯一項目數查詢

[英]MySQL Unique Item Count Query

我在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查詢呢? 謝謝。

假設每一行的customerName和customerGroup相同,則使用countcount以及group by distinct

select customerName
,customerGroup
,count(hasPurchase) as totalPurchase
,count(distinct hasPurchase) as uniquePurchase
from your_table
group by CustomerName,CustomerGroup
SELECT DISTINCT CustomerName,
                CustomerGroup,
                COUNT(hasPurchase) as totalPurchase,
                COUNT(DISTINCT hasPurchase) as uniquePurchase
FROM XXX
GROUP BY CustomerName,
         CustomerGroup

我沒有在MySQL上運行它,但是我認為它應該可以工作。

您可以為此嘗試分組

Count(hasPurchase)購買Count(hasPurchase)

Count(Distinct hasPurchase)用於唯一的購買

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM