选择第一行,其中下两行增加+ 1,(rowVal + 2)可以被3整除

时间:2016-06-15 13:02:24

标签: sql tsql

我已经准备好了@Gordon Linoff在那里部分回答了这个问题还有一个额外的要求。

我想找到后续n行值增加+ 1的第一行。

CREATE TABLE #Temp
    ([ID] int, [cct] int)
;

INSERT INTO #Temp
    ([ID], [cct])
VALUES
    (12807, 6),
    (12813, 12),
    (12818, 17),
    (12823, 22),
    (12824, 23),
    (12830, 29),
    (12831, 30),
    (12832, 31),
    (12833, 32),
    (12835, 34),
    (12837, 36),
    (12838, 37),
    (12839, 38),
    (12840, 39),
    (12841, 40),
    (12844, 43),
    (12846, 45),
    (12847, 46),
    (12848, 47),
    (12849, 48),
    (12850, 49),
    (12851, 50),
    (12854, 53),
    (12856, 55),
    (12857, 56),
    (12860, 59),
    (12862, 61),
    (12863, 62),
    (12864, 63),
    (12865, 64),
    (12866, 65),
    (12871, 70),
    (12872, 71),
    (12873, 72)
;

@Gordon已经提供了这段代码来查找序列部分。

  select min(id),min(cct) as cct, count(*) as length
from (select s.*, (cct - row_number() over (order by id)) as grp
      from #Temp s
     ) s
group by grp
having count(*) >= 3

这非常适合查找序列。从结果中可以看出。

ID  cct length
12830   29  4
12837   36  5
12846   45  6
12862   61  5
12871   70  3

但是我需要找到满足(cct + 2)%3 = 0的序列中的cct值

我需要查询返回ID 12838,cct 37,因为这是第一个cct值+ 2可被2整除,接下来的2行值增加1。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我想我已经理解了你需要的东西,试试这个:

;with
grp as (-- get the sequences as @Gordon suggested
    select s.*, (cct - row_number() over (order by id)) as grp
    from #Temp s
),
grp_seq as (-- get the sequence position of each id
    select *, ROW_NUMBER() over (PARTITION by grp order by cct) n
    from grp
),
grp_min_max as (-- get sequence informations min/max ID, start cct and sequence length, for each group
    select grp, min(id) min_id, max(id) max_id, min(cct) as cct, count(*) as length
    from grp_seq s
    group by grp
    having count(*) >= 3
)
-- finally join all toghether to retrieve your result
select t1.ID, t1.cct, '--------->' col_sep, t1.n seq_pos, t2.ID ID_cct2, t2.cct cct_div3, t3.*
from grp_seq t1
inner join grp_seq t2 on (t1.grp=t2.grp) and (t1.cct = t2.cct-2) and (t2.cct % 3 = 0) 
inner join grp_min_max t3 on t3.grp = t1.grp
order by id

它应该得到你所需要的一切

ID  cct col_sep seq_pos ID_cct2 cct_div3    grp min_id  max_id  cct length
12838   37  --------->  2   12840   39  25  12837   12841   36  5
12847   46  --------->  2   12849   48  28  12846   12851   45  6
12862   61  --------->  1   12864   63  34  12862   12866   61  5
12871   70  --------->  1   12873   72  38  12871   12873   70  3

我在结果记录的序列上添加了一些额外的信息(afer col_sep列),期望ID不能总是 cct + SomeValue ,这样它将为您提供所有可用的信息,剥离你不需要的东西。

我希望这会有所帮助