我在sql server查询中有问题,这里是
Table 1
Id |User |Start |End
====+=======+=======+======
1 | 5 | 1:00 | 2:00
2 | 5 | 2:00 | 3:00
3 | 5 | 3:00 | 4:00
4 | 5 | 7:20 | 8:35
5 | 7 | 3:00 | 4:30
Result
ID |User |Start |End |TotalAll |Running
====+=======+=======+=======+===========+========
1 |5 |1:00 | 2:00 | 3.0 | 1.0
2 |5 |2:00 | 3:00 | 3.0 | 2.0
3 |5 |3:00 | 4:00 | 3.0 | 3.0
4 |5 |7:20 | 8:35 | 1.25 | 1.25
5 |7 |3:00 | 4:30 | 1.5 | 1.5
由于会话1&2&3相互之间无间断连接,并且它们也是来自同一用户,因此我想再增加2列1,即该连接会话的总小时数为3.0小时2 ,即总运行时间,第一条记录为1小时,第二条记录为2小时,第三条记录为3小时。
主要问题是确定哪个是"connected" Id。为此,递归cte rcte查询用于根据Start和End时间进行识别
至于TotalAll和Running,这只是sum()与窗口功能一起使用
; with
cte as
(
select *,
rn = row_number() over (partition by [User] order by [Start])
from your_table t
),
rcte as
(
select *, grp = 1
from cte
where rn = 1
union all
select c.*,
grp = case when r.[End] = c.[Start] then r.grp else r.grp + 1 end
from rcte r
inner join cte c on r.[User] = c.[User]
and r.rn = c.rn - 1
)
select r.[Id], r.[User], r.[Start], r.[End],
TotalAll = sum(datediff(minute, [Start], [End]))
over (partition by [User], [grp]) / 60.0,
Running = sum(datediff(minute, [Start], [End]))
over (partition by [User], [grp]
order by Id) / 60.0
from rcte r
order by [Id]
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。