I have a set of milestones with random dates on table 1 and a set of items with random dates on table 2 (see below).
Table 1
Milestone | MilestoneDate |
---|---|
A | 01/01/2021 |
B | 03/15/2021 |
C | 05/27/2021 |
D | 09/09/2021 |
Table 2 (this table has hundreds of entries with different dates spanning the entire year)
ItemID | ItemCreateDate |
---|---|
1 | 01/17/2021 |
2 | 01/18/2021 |
3 | 01/25/2021 |
4 | 02/12/2021 |
... | ... |
I need to count the number of entries from table 2 with dates that fall between each milestone (see below).
Milestone | Items |
---|---|
A | 24 |
B | 31 |
C | 44 |
D | 37 |
My current query is:
SELECT
tbl2.Milestone
,COUNT(DISTINCT tbl1.ItemID) 'Items'
FROM
tbl1
FULL JOIN tbl2
ON tbl1.CreateDate = tbl2.MilestoneDate
GROUP BY
tbl2.Milestone,tbl2.MilestoneDate
ORDER BY
tbl2.MilestoneDate
Milestone | ItemCount |
---|---|
NULL | 136 |
I've tried any number of configurations to solve this, including just using the date instead of the milestone name, dropping the ORDER BY, as well as totally different coding approaches. What is the best way to solve this issue? NOTE: I cannot use the keys present in either table because they would result in tracking something totally different. I'm not the dba for this database, so I cannot adjust the tables themselves.
Currently I am having to pull each of these values manually by specifying each date range and running the query, then another date range and running (there are dozens of milestones with new ones being added constantly).