简体   繁体   中英

Count distinct items between start date and end date in MS Access

I have these two tables:

Table 1

| EventCode | StartDate |  EndDate  | Client |
|   13400   | 1/12/2014 | 5/12/2014 |   ABC  |
|   13400   | 6/12/2014 | 8/12/2014 |   ABC  |
|   15600   | 3/12/2014 | 5/12/2014 |   ABC  |

Table 2

| EventCode | Client | SignUpDate | Agent |
|   13400   |   ABC  |  2/12/2014 | AG001 |
|   13400   |   ABC  |  2/12/2014 | AG001 |
|   13400   |   ABC  |  3/12/2014 | AG002 |
|   15600   |   ABC  |  4/12/2014 | AG002 |
|   15600   |   ABC  |  4/12/2014 | AG004 |
|   15600   |   ABC  |  5/12/2014 | AG002 |
|   13400   |   ABC  |  7/12/2014 | AG003 |

I need to join the two tables WHERE Table2.SignUpDate BETWEEN Table1.StartDate AND Table1.EndDate , then I need a distinct count of Agents from Table 2, to get how many distinct persons did sales for every event, like the one below:

| EventCode | StartDate |  EndDate  | Client |  CountOfDistinctAgents |
|   13400   | 1/12/2014 | 5/12/2014 |   ABC  |           2            | //(AG001, AG002)
|   13400   | 6/12/2014 | 8/12/2014 |   ABC  |           1            | //(AG003)
|   15600   | 3/12/2014 | 5/12/2014 |   ABC  |           2            | //(AG002, AG004)

But I am having trouble getting the above output because I need to do this in MS ACCESS 2003 . Please help me.

This is my old code, but it doesn't count the DISTINCT agents.

SELECT tmp.[Event Code], eb.CampaignLN, eb.StartDate, eb.EndDate, COUNT(*) AS HeadCount
FROM 
(SELECT DISTINCT [Event Code], Campaign, [Signup Date], [Agent Id] FROM [Main Table2]) AS tmp 
INNER JOIN qryGetEventBookings AS eb ON (tmp.[Signup Date] BETWEEN CDATE(eb.StartDate) AND  
CDATE(eb.EndDate)) AND (eb.CampaignLN=tmp.Campaign) AND (eb.LocationCode=tmp.[Event Code])
GROUP BY tmp.[Event Code], eb.CampaignLN, eb.StartDate, eb.EndDate;

I greatly appreciate all of your help. Thanks in advance.

To count the distinct agents, you need to use a subquery (because MS Access does not support count(distinct) ). The result is something like this:

SELECT [Event Code], COUNT(*) AS NumAgents
FROM (SELECT DISTINCT m.EventCode, eb.Agent
      FROM  [Main Table2] as m JOIN
            qryGetEventBookings eb
            ON eb.CampaignLN = m.Campaign AND eb.LocationCode = m.[Event Code] AND
               eb.SignUpDate BETWEEN m.StartDate AND m.EndDate
     ) AS tmp 
GROUP BY [Event Code];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM