在SQL Server中按优先级裁剪重叠的时间跨度

时间:2012-09-24 09:41:42

标签: sql-server timespan gaps-and-islands

我有一个大型数据库表,其中包含由startstop时间描述的时间跨度。简易时间跨度优先,时间跨度可能相互重叠。

我需要处理它以便删除重叠 在重叠的情况下,具有较高优先级的跨度将优先,并且具有较低优先级的时间跨度将被裁剪,使得两者不重叠。 如果时间跨度与一个或多个具有更高优先级的时间跨度完全重叠,则应将其删除。

一个简单的示例表:

SELECT
    1 AS id,
    {ts '2012-09-24 10:00:00'} AS start,
    {ts '2012-09-24 11:00:00'} AS stop,
    10 AS priority
INTO #TABLE
UNION ALL SELECT 2, {ts '2012-09-24 10:15:00'}, {ts '2012-09-24 12:00:00'}, 5
UNION ALL SELECT 3, {ts '2012-09-24 10:30:00'}, {ts '2012-09-24 12:30:00'}, 1
UNION ALL SELECT 4, {ts '2012-09-24 11:30:00'}, {ts '2012-09-24 13:00:00'}, 15

SELECT * FROM #TABLE;
DROP TABLE #TABLE;

应该导致:

Start              Stop               Priority
2012-09-24 10:00   2012-09-24 11:00   10
2012-09-24 11:00   2012-09-24 11:30   5
2012-09-24 11:30   2012-09-24 13:00   15

有可能,但我找不到任何简单的解决方案。我最好避免使用游标。但是,如果没有别的办法,那就是光标。

1 个答案:

答案 0 :(得分:2)

尝试

;with cte as 
(select start as timepoint from @table union select stop from @table)
,cte2 as (select *, ROW_NUMBER() over (order by timepoint) rn from cte) 

    select id, MIN(ts) as starttime, max(te) as stoptime, maxpri
    from @table t2
        inner join
        (               
        select ts, te, MAX(priority) as maxpri 
        from @table t1
            inner join
            (       
            select c1.rn, c1.timepoint as ts, c2.timepoint as te 
            from cte2 c1
            inner join cte2 c2 on c1.rn+1 = c2.rn
            ) v
            on t1.start<v.te and t1.stop>v.ts
        group by ts, te
        ) v
            on t2.priority = v.maxpri
            and ts>=start and te<=stop
        group by id, maxpri
        order by starttime