我已经问过与此SQL Daily Outstanding Sales, Rolling Aggregate?类似的问题,但是我现在需要每天了解销售的持续时间。这将分为24小时(或一天)间隔,最多72小时。下面是数据集输出的一个示例,超时将在一个组内,但是日期必须是any日期,即使它不在数据集中也是如此(可以在2020-01-02上看到)第二行
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
数据集
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
首先,您可以用新的和完成的日期汇总每个Salesid。然后,生成您关心的日期。并使用条件聚合:
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