栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从日期时间表中获取包含开始和结束值的列表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从日期时间表中获取包含开始和结束值的列表

– Table var to store the gaps
declare @T table
(
DeviceID varchar(10),
PrevPeriodEnd datetime,
NextPeriodStart datetime
)

-- Get the gaps;with cte as (  select *,    row_number() over(partition by DeviceID order by Timestamp) as rn  from data)insert into @Tselect  C1.DeviceID,  C1.Timestamp as PrevPeriodEnd,  C2.Timestamp as NextPeriodStartfrom cte as C1  inner join cte as C2    on C1.rn = C2.rn-1 and       C1.DeviceID = C2.DeviceID and       datediff(s, C1.Timestamp, C2.Timestamp) > 5-- Build islands from gaps in @T;with cte1 as(  -- Add first and last timestamp to gaps  select DeviceID, PrevPeriodEnd, NextPeriodStart  from @T  union all  select DeviceID, max(TimeStamp) as PrevPeriodEnd, null as NextPeriodStart  from data  group by DeviceID  union all  select DeviceID, null as PrevPeriodEnd, min(TimeStamp) as PrevPeriodEnd  from data  group by DeviceID),cte2 as(  select *,    row_number() over(partition by DeviceID order by PrevPeriodEnd) as rn  from cte1)select  C1.DeviceID,  C1.NextPeriodStart as PeriodStart,  C2.PrevPeriodEnd as PeriodEndfrom cte2 as C1  inner join cte2 as C2    on C1.DeviceID = C2.DeviceID and       C1.rn = C2.rn-1order by C1.DeviceID, C1.NextPeriodStart


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456348.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号