繁体   English   中英

计数不同?

[英]Count Distinct?

我有一张“购买”表:

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

我正在尝试计算每个月和每年购买的客户数量。 我该怎么做?

只要您不需要包括没有购买的月份:

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

请注意, COUNT(DISTINCT xxx)适用于所有主要 SQL 系统,但在某些系统上不受支持(如 MS Access)。

每年的客户购买量

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

客户按月购买

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

您可以使用 group by 的常见查询来实现您想要的结果。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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