简体   繁体   中英

Find out how many tickets were open each day historically

I have a table that looks like the below

 ID   | CreatedDate   |  CloseDate
271   | 01-Jan-2018   |  02-Jan-2018
278   | 03-Jan-2018   |  05-Jan-2018
333   | 03-Jan-2018   |     NULL

I have been tasked to find out for each day in a month, how many tickets remained open going into the next day. A ticket would be classed as remaining open if the CloseDate was not on the same date as the created date, or the CloseDate is NULL.

My ideal output from the above would look like this

Day          | Tickets Remaining
01-Jan-2018  |        1
02-Jan-2018  |        0
03-Jan-2018  |        2
04-Jan-2018  |        2
05-Jan-2018  |        1

Does this make sense? Using SQL Server 2016..

If you don't have a number/tally table handy, you can use a recursive CTE:

with cte as (
      select id, createddate as dte, coalesce(closeddate, convert(date, getdate())) as closeddate
      from t
      union all
      select id, dateadd(day, 1, dte), closeddate
      from cte
      where dte < closeddate
     )
select dte, count(*)
from cte
group by dte;

Note: If any of the timespans can exceed 100 days, then you need to add option (maxrecursion 0) .

If there are only a handful of dates, you can use a derived table and left join :

select v.dte, count(t.id)
from (values (convert(date, '2018-01-01')),
             (convert(date, '2018-01-02')),
             (convert(date, '2018-01-03')),
             (convert(date, '2018-01-04')),
             (convert(date, '2018-01-05')),
     ) v(dte) left join
     t
     on v.dte >= t.createddate and
        (v.dte <= t.closeddate or t.closeddate is null)
group by v.dte
order by v.dte;

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