I have a date table, and I have a table with tickets that have an open date field and a close date field. I need to count the number of tickets which were open on each calendar day
ie.
Date Table
| Date | Year |
| ------------ | ------------ |
| 2021-02-19 | 2021 |
| 2021-02-20 | 2021 |
| 2021-02-21 | 2021 |
| 2021-02-22 | 2021 |
| 2021-02-23 | 2021 |
| 2021-02-24 | 2021 |
Ticket Table
Ticket # | Opened Date | Closed Date |
---|---|---|
00000001 | 2021-02-01 | 2021-02-23 |
00000001 | 2021-02-16 | 2021-02-19 |
00000001 | 2021-02-21 | Null |
00000001 | 2021-10-01 | 2021-01-23 |
00000001 | 2021-02-01 | 2021-02-19 |
00000001 | 2021-02-05 | 2021-02-19 |
00000001 | 2021-02-01 | 2021-02-18 |
00000001 | 2021-02-23 | 2021-02-24 |
00000001 | 2021-02-22 | 2021-02-22 |
00000001 | 2021-02-01 | 2021-02-21 |
I haven't tried anything because I am not sure where to start. I assume it would be beneficial to join with the date table which is why I added it to my question here.
SQL 2015
Thanks in Advance
2条答案
按热度按时间olhwl3o21#
I would unpivot the tickets table to compute the backlog on any given day, then bring the dates table with a join.
The upside of this solution is that is scans the tickets table only once, as opposed to other options involving a correlated subquery with inequality conditions (or a lateral join), that needs to be re-executed for each and every date.
mlmc2os52#
When asking questions like this it's really helpful to provide easily reproducible DDL/DML. This makes it easier for folks to answer your question.
Consider:
I've adjusted your example data here as I think you intended the ticket numbers to be different for each row.
To produce a result set which shows the number of open tickets all you really need is a
LEFT OUTER JOIN
from the dates table to the tickets table. Since we want the date to be within a range (which is essentially endless when there is no closed date) we can use aBETWEEN
as the predicate, and then aggregate by the date. ALEFT OUTER JOIN
is used so we get a 0 when there are no tickets for that day. UsingINNER JOIN
would result in the row being excluded from the result set.