How to group by on consecutive values in SQL

后端 未结 2 1761
日久生厌
日久生厌 2021-01-28 13:59

I have a table in SQL Server 2014 with sample data as follows.

WK_NUM | NET_SPRD_LCL 
10       0 
11       1500 
12       3600 
13       3800 
14       4000

2条回答
  •  隐瞒了意图╮
    2021-01-28 14:42

    Assuming you mean consecutive line 1, 2, 3, 4, 5 ... etc. and NOT 1, 3, 5, 8, 12, etc.

    then, if you don't need to know which pair of consecutive records it was:

    Select case when exists
       (Select * from table f
           join table n
              on n.Wk_Num = f.Wk_Num + 1
                 and n.NET_SPRD_LCL > 3500
                 and f.NET_SPRD_LCL > 3500
                 and n.Wk_Num < 27
        then 2000 else null end
    

    If you do need to identify the pair of records, then:

    Select f.wk_Num firstWorkNbr, f.NET_SPRD_LCL firstNetSpread,
           n.wk_Num nextWorkNbr, n.NET_SPRD_LCL nextNetSpread
    from table f
       join table n
           on n.Wk_Num = f.Wk_Num + 1
             and n.NET_SPRD_LCL > 3500
             and f.NET_SPRD_LCL > 3500
              and n.Wk_Num < 27
     Where not exists 
        (Select * from table f0
           join table n0 
               on n0.Wk_Num = f0.wk_Num + 1
                  and n0.WkNum < f.Wk_Num))
    

    on the other hand if the consecutive is simply increasing, then it's a bit harder. You need to use a subquery to determine the next consecutive record...

    Select case when exists
       (Select * from table f
           join table n
              on n.Wk_Num = (Select Min(Wk_Num) from table
                             Where Wk_Num > f.Wk_Num)
                 and n.NET_SPRD_LCL > 3500
                 and f.NET_SPRD_LCL > 3500
                 and n.Wk_Num < 27
        then 2000 else null end
    

    and if you need to fetch the data for the specific first pair of records that qualify (the 2000 at the end is unnecessary since if there is no qualifying pair nothing will be returned.)

    Select f.wk_Num firstWorkNbr, f.NET_SPRD_LCL firstNetSpread,
           n.wk_Num nextWorkNbr, n.NET_SPRD_LCL nextNetSpread, 2000 outValue
    from table f
       join table n
           on n.Wk_Num = (Select Min(Wk_Num) from table
                          Where Wk_Num > f.Wk_Num)
             and n.NET_SPRD_LCL > 3500
             and f.NET_SPRD_LCL > 3500
              and n.Wk_Num < 27
     Where not exists 
        (Select * from table f0
           join table n0 
               on n0.Wk_Num = (Select Min(Wk_Num) from table
                               Where Wk_Num > f0.Wk_Num)
                  and n0.WkNum < f.Wk_Num))
    

提交回复
热议问题