我有一张顾客和商店的桌子。商店代表他们从我这里购买东西的地方。我想计算他们从每家商店购买了多少次以及他们从任何商店购买东西的总次数。
样本表名为PURCHASE:
Customer Store ABC Store 1 ABC Store 2 ABC Store 2 ABC Store 3 ABC Store 3 ABC Store 4 ABC Store 4 ABC Store 4
我想要的结果:
Customer Store Count Total ABC Store 1 1 8 ABC Store 2 2 8 ABC Store 3 2 8 ABC Store 4 3 8
我尝试过这样的事情,但由于记录超过40,000,所以花了很长时间:
SELECT a.customer, store, count(a.customer) AS thisstore
FROM PURCHASE a
LEFT JOIN
(
SELECT COUNT(customer) AS totalsales,customer
FROM PURCHASE
GROUP BY customer) b
ON b.customer=N.customer GROUP BY a.customer;
如果有人知道更好的方法,请告诉我 - 谢谢。
答案 0 :(得分:0)
此查询将为您提供所要求的输出,如果您在PURCHASE.customer
上有索引,则应该更快:
SELECT a.customer, a.store, count(*) AS thisstore
, (select count(*) from PURCHASE b where b.customer=a.customer) as total
FROM PURCHASE a
GROUP BY a.customer,a.store