我有一张桌子"购买":
CustomerId . PurchaseYear . PurchaseMonth
1234 . 2012 . 6
1235 . 2012 . 7
1236 . 2013 . 4
1237 . 2015 . 6
1238 . 2015 . 6
我试图计算每个月和每年购买的客户数量。我该怎么做呢?
答案 0 :(得分:2)
只要您不需要包含没有购买的月份:
SELECT PurchaseYear, PurchaseMonth, COUNT(DISTINCT CustomerId)
FROM {table}
GROUP BY PurchaseYear, PurchaseMonth
请注意COUNT(DISTINCT xxx)
适用于所有主要的SQL系统,但某些(例如MS Access)不支持。
答案 1 :(得分:0)
按年度购买客户
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
答案 2 :(得分:0)
您的愿望结果可以使用分组的常见查询来实现。
Select PurchaseYear , PurchaseMonth, Count(CustomerId) as TotalCustomer,
From Purchase
Group by PurchaseYear, PurchaseMonth