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

在SQL中合并具有重叠日期范围的记录

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

在SQL中合并具有重叠日期范围的记录

这是我能够弄清楚的2008年最简单的版本:

; with Data (Date) as (select StartDate from Datesunionselect EndDate from Dates),Ranges (StartDate, Status) as (select D.Date, D2.Statusfrom Data Douter apply (  select top 1 D2.Status  from Dates D2  where D2.StartDate <= D.Date and D2.EndDate > D.Date  order by case when Status = 'on' then 1 else 2 end) D2)select R.StartDate,(select min(D.Date) from Data D where D.Date > R.StartDate) as EndDate,Statusfrom Ranges Rorder by R.StartDate

即使状态与以前相同,它也会从每个起点/终点开始返回新行。没有找到任何简单的方法来组合它们。

编辑:将第一个CTE更改为此将合并行:

; with Data (Date) as (select distinct StartDate from Dates D1where not exists (Select 1 from Dates D2     where D2.StartDate < D1.StartDate and D2.EndDate > D1.StartDate and    Status = 'on')unionselect distinct EndDate from Dates D1where not exists (Select 1 from Dates D2     where D2.StartDate < D1.EndDate and D2.EndDate > D1.EndDate and    Status = 'on')),


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

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

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