Minnow said:
I want to count how many orders a customer placed in a month, in the case of
a customer did place order in that month, I want it show me 0. Unfortunately,
my statement does not show me the customer without a order. Any idea? the
following is the statement:
Select CustomerID, iif(Count(orders) is null, 0, Count(orders)) from Orders
where Month(OrderDate=5)
Try this:
Select CustomerID, Count(nz(Orders,0)) As CountOfOrders FROM tblCustomers
LEFT JOIN Orders ON tblCustomers.CustomerID=Orders.CustomerID WHERE Month
(OrderDate)=5
(I assume your last few characters are simply a typo.) If you don't have a
separate table for customers (I assume in my SQL that you do) then your data
is not normalized properly; I suggest you put customer data into a separate
table (see the Access help file on normalization) before continuing. Also, if
you're not familiar with different joins, or the nz() function, see the help
file about them too.
Alternatively, you can arrange all your CustomerIDs into a separate sub-query,
as follows:
Select CustomerID FROM Orders GROUP BY CustomerID
Let's call that qryCustOrd. Now your main query can be as follows:
Select CustomerID, Count(nz(Orders,0)) As CountOfOrders FROM qryCustOrd LEFT
JOIN Orders ON qryCustOrd.CustomerID=Orders.CustomerID WHERE Month(OrderDate)
=5
That should give you the data you want.
Also, to give you more flexibility, you can change the last part of the SQL
to:
WHERE Month(OrderDate)=[Enter Month Number] And Year(OrderDate)=[Enter Year]
That forces the user to enter the month number and year each time he runs the
query; you don't have to hard-code the information right in the SQL. Also, if
he wants historical data, it's available at the touch of a button.