I’m trying to query my SQL database to get the number of orders made by each client within a certain date range.
I have a list of orders as follows
CustomerName ClientID DateOrdered
Customer No.2 10 2011-11-25
Customer No.3 11 2011-10-15
Customer No.3 11 2011-11-25
and I want to be able to find out how many orders have been made by a specific client for example between 2011-11-1 and 2011-11-30, this should result in :
CustomerName ClientID Number
Customer No.3 11 1
Customer No.2 10 1
So far I’ve managed to get this
SELECT CustomerName, ClientID, COUNT(*) AS Number
FROM Orders t
GROUP BY CustomerName, ClientID
HAVING COUNT(*) =
(SELECT MAX(Number)
FROM
(SELECT CustomerName, ClientID, COUNT(*) AS Number
FROM Orders
GROUP BY CustomerName, ClientID ) x
WHERE CustomerName = t.CustomerName )
Which gives me every order the customer has ever made
CustomerName ClientID Number
Customer No.3 11 2
Customer No.2 10 1
Am I going about the right way to solve this or is there a simpler way which I’ve completely overlooked!
What this does is utilize a subquery that filters the rows by the dates in a given month (that seems to be what you are looking for). Then it groups by the
CustomerNameandClientIDand gets the sum of their orders.