Question : How can I Return a fictitious row into a result set?

The following query does a count of rows grouped by Date and Sales person.  I need to give all the dates sales person with no rows a count of zero. Is there a way to do this in the query itself?


1:
2:
3:
4:
5:
SELECT s.eventStartDate, s.salesPersonID, Count(s.salesEventID) AS CountEvent
FROM smd_salesEvent s
WHERE (((s.saleTypeID)=1) AND ((s.storeID)<>0) AND ((s.saleEventStatus)<>"Discontinue"))
GROUP BY s.eventStartDate, s.salesPersonID
HAVING (((s.eventStartDate) Between #7/4/2010# And #7/10/2010#));

Answer : How can I Return a fictitious row into a result set?

To take cyberkiwi one step further you could try the following.  WHERE Richard chose to select DISTINCT Date, people combinations, the following will return a cartesian join of date/people (subtle difference).

SELECT eDatePeople.eventStartDate, eDatePeople.SalesPersonID, Count(S3.SalesEventID) as CountEvent
FROM (
SELECT eDates.EventStartDate, ePeople.SalesPersonID
FROM
(SELECT DISTINCT S1.eventStartDate FROM smd_salesEvent S1
WHERE S1.EventStartDate BETWEEN #7/4/2010# and #7/10/2010#
AND S1.SaleTypeID = 1 AND S1.StoreID <> 0 AND S1.SaleEventStatus <> "Discontinue") as eDates,
(SELECT DISTINCT S2.salesPersonID FROM smd_salesEvent S2
WHERE S2.EventStartDate BETWEEN #7/4/2010# and #7/10/2010#
AND S2.SaleTypeID = 1 AND S2.StoreID <> 0 AND S2.SaleEventStatus <> "Discontinue") as ePeople
) as eDatePeople
LEFT JOIN smd_salesEvent S3
ON eDatePeople.eventStartDate = S3.eventStartDate
AND eDatePeople.SalesPersonID = S3.SalesPersonID
GROUP BY eDatePeople.eventStartDate, eDatePeople.SalesPersonID

This has two subqueries that select the distinct dates (eDates) and the distinct people (ePeople) that correspond to the criteria you have selected.  It then merges them in a cartesian join (eDatePeople) that gives you every combination of every date/person for those criteria.  Finally it joins eDatePeople back to smd_SalesEvent to get the count of SalesEventID for each date/person combination.

What it does not do is guarantee that you will have all of the dates which occur between your start and end date, since the other criteria could return zero records, or some subset of values.  It also only returns records for those sales people that have at least one record which meets your criteria.  If a person is on vacation or did not participate in any sales event during the period specified, their name will not show up at all.

If you would like to ensure that all dates during a time span are returned, you could use a table of dates to come up with the eDates portion of the query instead of the subquery I used.
Random Solutions  
 
programming4us programming4us