我有2张桌子:成员,订单。
Members: MemberID, DateCreated
Orders: OrderID, DateCreated, MemberID
我想知道一个月内新成员的数量,这些成员被分解为多个订单组,例如。 5 +,4,3,2,1,0
我有查询来计算成员的订单数量,但我怎样才能在一个查询中获得这些值?
SELECT
COUNT(o.orderid) AS Purchases
FROM
members m
LEFT JOIN orders o ON o.memberid = m.memberid
AND MONTH(o.DateCreated) = 8
WHERE
MONTH(m.DateCreated) = 8
GROUP BY
m.memberid
ORDER BY
COUNT(o.orderid) DESC
答案 0 :(得分:4)
答案 1 :(得分:1)
有几种方法可以做到这一点,其中一些可能相当复杂。
这就是我的方式,专注于新成员而不是计数部分:
SELECT COUNT(M.MemberID),
(SELECT COUNT(*) FROM Orders O WHERE O.MemberId = M.MemberId AND O.DateCreated BETWEEN '2010-08-01' AND DATE_ADD('2010-08-01', INTERVAL 1 MONTH)) AS num_orders
FROM Members M
WHERE M.DateCreated BETWEEN '2010-08-01' AND DATE_ADD('2010-08-01', INTERVAL 1 MONTH)
GROUP BY num_orders
我使用日期进行查找,因为它会更快(它可以使用索引,而MONTH(M.DateCreated)
总是会进行全表扫描,但如果确实需要所有订单/成员,您可以将其更改回来从某个月开始。)
编辑: 我忘了处理问题的5+部分,所以这里有一个选项:
SELECT COUNT(M.MemberID),
(SELECT IF(COUNT(*) >= 5, '5+', COUNT(*)) FROM Orders O WHERE O.MemberId = M.MemberId AND O.DateCreated BETWEEN '2010-08-01' AND DATE_ADD('2010-08-01', INTERVAL 1 MONTH)) AS num_orders
FROM Members M
WHERE M.DateCreated BETWEEN '2010-08-01' AND DATE_ADD('2010-08-01', INTERVAL 1 MONTH)
GROUP BY num_orders