0

start我有一个大型数据库表,其时间跨度由时间描述stop。简单的时间跨度具有优先级,并且时间跨度可能相互重叠。

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

一个简单的示例表:

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

这是可能的,但我找不到任何简单的解决方案。最好我想避免使用游标。但如果没有其他办法,好吧,游标它就是。

4

1 回答 1

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
于 2012-09-24T10:21:33.673 回答