简体   繁体   中英

Count Distinct?

I have a table "Purchases":

CustomerId . PurchaseYear . PurchaseMonth
1234       . 2012         . 6 
1235       . 2012         . 7
1236       . 2013         . 4
1237       . 2015         . 6
1238       . 2015         . 6

And I'm trying to count the number of customers who made a purchase in each month and year. How do I go about doing this?

So long as you don't need to include months where no purchase was made:

SELECT PurchaseYear, PurchaseMonth, COUNT(DISTINCT CustomerId)
FROM {table}
GROUP BY PurchaseYear, PurchaseMonth

Note that COUNT(DISTINCT xxx) works with all of the major SQL Systems but is not supported on some (like MS Access).

Customer Purchases by Year

Select PurchaseYear, Count(DISTINCT CustomerId) As CustomerPurchases
FROM Purchases
GROUP BY PurchaseYear

Customer Purchases by Month

Select PurchaseYear, PurchaseMonth, Count(DISTINCT CustomerId) As CustomerPurchases
FROM Purchases
GROUP BY PurchaseYear, PurchaseMonth

Your desire result can be achieve using common query of group by.

Select PurchaseYear , PurchaseMonth, Count(CustomerId) as TotalCustomer, 
From Purchase 
Group by PurchaseYear, PurchaseMonth

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM