Skip to content
Advertisement

SQL How Long Have Incomplete Records Been Outstanding Broken Down By Day

I have asked a similar question to this SQL Daily Outstanding Sales, Rolling Aggregate? however I now need to understand, by day, how long sales have been outstanding. This will be grouped into 24 hours (or day) intervals to a max of 72hours. An example of the output from the Dataset is below, Timeoutstanding would be within a group by however Date needs to be any date, even if it was not within the DataSet which can be seen with 2020-01-02 on the second row

Date         TimeOutstanding    VolumeOutstanding  
2020-01-01   Under24Hour        1                                   
2020-01-02   Under48Hour        1
2020-01-03   Under24Hour        3
2020-01-03   Under72Hour        1
2020-01-04   Under48Hour        3
2020-01-05   Under72Hour        2
2020-01-05   Over72Hour         1 

DataSet

SaleID   Date         Outcome
1        2020-01-01   New
1        2020-01-01   Complete
2        2020-01-01   New
3        2020-01-03   New
4        2020-01-03   New
5        2020-01-03   New
2        2020-01-04   Complete
5        2020-01-04   Complete
3        2020-01-06   Complete
4        2020-01-07   Complete

Advertisement

Answer

First, you can summarize each salesid with the new and completed date. Then, generate the dates that you care about. And use conditional aggregation:

select d.date,
       count(*) as num_open,
       sum(case when new_date >= dateadd(day, -1, d) then 1 else 0
           end) as within_1day,
       sum(case when new_date < dateadd(day, -1, d)  and new_date >= dateadd(day, -3, d then 1 else 0
           end) as within_1_3days_ago,
       . . .
from (select distinct date from t) d left join
     (select salesid, min(date) as new_date,
             nullif(max(date), min(date)) as completed_date
      from t
      group by salesid
     ) t
     on new_date <= date and (date < completed_date or completed_date is null)
group by d.date
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement