以下数据格式的SQL表
Datetime Type Id
6/18/2018 8:00:00 A 1
6/18/2018 9:00:00 A 2
6/18/2018 10:00:00 A 3
6/18/2018 11:00:00 B 4
6/18/2018 12:30:00 B 5
6/18/2018 13:15:00 A 6
6/18/2018 14:00:00 A 7
需要结果表
Type Startdate Enddate Count Changeovertime
A 6/18/2018 8:00:00 6/18/2018 10:00:00 3 NA
B 6/18/2018 11:00:00 6/18/2018 12:30:00 2 1:00:00
A 6/18/2018 13:15:00 6/18/2018 14:00:00 2 0:45:00
你能帮我查询一下结果吗?
我正在使用sql server 2008 express edition。
此致 Dilipan。
答案 0 :(得分:1)
您可以使用row_number()
的差异:
select Type, min(datetime) as startdate, max(datetime) as enddate, count(*) as count
from (select *, row_number() over (partition by type order by id) seq
from table
) t
group by Type, (Id-Seq);