查找日期顺序

时间:2018-09-26 02:38:53

标签: sql sql-server tsql sequence

我有一张这样的桌子:

id             date        
1             2018-01-01 01:01
2             2018-01-02 14:00
3             2018-01-01 05:00  -- affected
4             2018-01-03 16:0

我想搜索日期序列(按循环)是否按升序排列,如果不是,则插入到另一个表中,如下所示:

还插入了受影响日期的上一个和下一个值。

 id             date        
    2             2018-01-02 14:00
    3             2018-01-01 05:00  
    4             2018-01-03 16:00

你们可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:0)

首先找到错误行,然后再获取该行之前和之后的行。

如果ID不连续,则使用row_number()生成连续序列号

; with 
tbl as      -- sample data
(
    select id = 1, date = '2018-01-01 01:01'    union all
    select id = 2, date = '2018-01-02 14:00'    union all
    select id = 3, date = '2018-01-01 05:00'    union all
    select id = 4, date = '2018-01-03 16:00'
),
cte as      -- the query
(
    select  *,
            prev    = LAG (date) OVER (ORDER BY id),
            seq     = ROW_NUMBER() OVER (ORDER BY id)   -- added this
    from    tbl t
),
err as      -- the error rows
(
    select  *
    from    cte
    where   date    < prev  
)
            -- the final result
select  c.*
from    err e
        inner join cte c    on  c.seq   >= e.seq - 1
                           and  c.seq   <= e.seq + 1