SQL Server +检索数据而不重叠日期时间

时间:2017-12-19 21:15:20

标签: sql-server date distinct recursive-query overlapping

我需要对本案的最佳实施提出一些想法

我有数据,其中可以有多个值,包括start&结束日期时间,现在我需要拉取数据而不重叠日期,下面是样本数据。

CREATE TABLE table2 (
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  comments VARCHAR(100)  NULL ,
  id int
);

INSERT INTO table2 (start_date, end_date, id) VALUES
('2011-12-01', '2012-01-02', 5),
('2012-01-01', '2012-01-06', 5),
('2012-01-05', '2012-01-10', 5),
('2012-01-09', '2012-01-11', 5);

从这里我需要每个id不重叠的数据

('2011-12-01', '2012-01-02', 5),
('2012-01-05', '2012-01-10', 5)

请与我分享关于哪种手杖是实施此手段的最佳方式的想法?

感谢您的支持

谢谢, 的Manoj。

2 个答案:

答案 0 :(得分:2)

您提供的输出非常不清楚。在第一眼看到你正在寻找一个intervall,其中没有其他intervall开始(这将导致持续的intervall)。但您的第二个预期行与2012-01-10重叠?

如果其end_date不在另一行intervall中,则以下查询将返回一行...但这不会返回您的两个预期行,只是第一行。

SELECT * FROM table2 AS t
WHERE NOT EXISTS(SELECT 1 
                 FROM table2 AS x 
                 WHERE x.start_date<>t.start_date 
                   AND x.end_date BETWEEN t.start_date AND t.end_date
                );

我希望这能指出正确的方向......

答案 1 :(得分:0)

以下将会这样做:

WITH cte
AS
(   
    SELECT
        [start_date]
        , end_date
        , comments
        , id
    FROM
        (
            SELECT
                [start_date]
                , end_date
                , comments
                , id
                , ROW_NUMBER() OVER (PARTITION BY id ORDER BY [start_date]) R
            FROM table2
        ) Q
    WHERE R = 1

    UNION ALL

    SELECT
        [start_date]
        , end_date
        , comments
        , id
    FROM
        (
            SELECT
                T.[start_date]
                , T.end_date
                , T.comments
                , T.id
                , ROW_NUMBER() OVER (PARTITION BY T.id ORDER BY T.[start_date]) R
            FROM
                cte C
                JOIN table2 T ON
                    C.id = T.id
                    AND T.[start_date] > C.end_date
        ) Q
    WHERE R = 1
)

SELECT
    [start_date]
    , end_date
    , comments
    , id
FROM cte