I have 2 tables: members, orders.
Members: MemberID, DateCreated
Orders: OrderID, DateCreated, MemberID
I want to find out the number of new members in a given month broken down into number of order groups, eg. 5+, 4, 3, 2, 1, 0
I’ve got the query to work out the number of orders for a member but how can I get these values in one query?
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
There’s a couple ways you can do this, some of which could be fairly complicated.
This is the way I would do, focusing on the new member part rather than the count part:
I did the lookup with dates because it would be faster (it could make use of an index whereas
MONTH(M.DateCreated)would always do a full table scan, but you can change it back if really do need all orders/members from a given month).EDIT:
I forgot to handle the 5+ part of the question so here’s an option for that: