数据看起来像下面-我想要的输出是,当一天中的下一个条目是相同的值时,这些时间将相加以获得总时间。值更改后,将第一个条目(该值)的日期更改为新值,以便获得该值持续的总时间。
Value Date
60 1/5/2019 8:00
60 1/5/2019 9:00
60 1/5/2019 10:00
75 1/5/2019 10:30
60 1/5/2019 11:00
40 1/5/2019 12:00
40 1/5/2019 13:00
所需的输出
Value Total Time
60 1/5/2019 8:00 - 10:30 = 2 and a half hours
75 1/5/2019 10:30 - 11:00 = half hour
60 1/5/2019 11:00 - 12:00 = 1 hour
40 1/5/2019 12:00 - 13:00 = 1 hour
答案 0 :(得分:1)
这是一个空白和孤岛的问题。对于此版本,我认为行号之间的差异是最简单的解决方案。因此,这几乎可以解决您的问题:
select value, min(date), max(date)
from (select t.*,
row_number() over (order by date) as seqnum,
row_number() over (partition by value order by date) as seqnum_v
from t
) t
group by (seqnum - seqnum_v), value;
但是您要 next 开始,所以我们也需要lead()
:
select value, min(date) as startdate,
lead(min(date), 1, max(date)) over (order by min(date)) as enddate
from (select t.*,
row_number() over (order by date) as seqnum,
row_number() over (partition by value order by date) as seqnum_v
from t
) t
group by (seqnum - seqnum_v), value;
并获取总时间:
select value,
datediff(minute,
min(date),
lead(min(date), 1, max(date)) over (order by min(date))
) as dur_minutes
from (select t.*,
row_number() over (order by date) as seqnum,
row_number() over (partition by value order by date) as seqnum_v
from t
) t
group by (seqnum - seqnum_v), value;