根据行拆分记录

时间:2019-03-28 05:07:29

标签: sql sql-server

我需要根据输入值@ExcludeFrom和@ExcludeTo提供的范围来拆分项目。

下面是我的@itemrange表。

    Declare @ItemRange table
    (
        Id int primary key, 
        ItemId int,
        [FROM] int,
        [To] int
    )


    INSERT INTO @ItemRange
    VALUES  
    (1,1,1,10000000),
    (2,2,101,500),
    (3,2,600,700)


Declare @ExcludeFrom as int =500000 ,  @ExcludeTo as int =700000 , @ItemId as int =1

预期结果将是:( [to]= (@ExcludeFrom-1) and [From]= (@ExcludeTo+1)

enter image description here

注意:范围差异超过1000万。

1 个答案:

答案 0 :(得分:1)

我们可以在这里尝试日历表方法,其中日历表包含您要匹配的范围:

WITH cte AS (
    SELECT 1 AS start, 499999 AS end UNION ALL
    SELECT 700001, NULL
)

SELECT
    t2.ItemId,
    t1.start,
    COALESCE(t1.[end], t2.[To]) AS [end]
FROM cte t1
INNER JOIN ItemRange t2
    ON (t2.[From] <= t1.[end] OR t1.[end] IS NULL) AND t2.[To] >= t1.start
WHERE
    t2.ItemId = 1;

enter image description here

Demo