oracle sql起始范围结束范围与计数

时间:2014-09-26 12:15:27

标签: sql oracle range

这是我查询的表格:

lcn_code   start_num      end_num
company1         1          1
company1         3          3
company1         5          5
company1         6          6
company1         7          7
company2         2          2
company2         4          4
company2         9          9
company2         8          8

如您所见,top_num到end_num的第一行是1& 1因此它是1的计数,但是在公司1下是一个序列中断,它们的下一个数字是3.所以我不想要' 2' 2根据公司1报告。我能这样做(只是)。

我遇到的问题如下: 在第3行和第5行之间没有序列中断.5,6,7所以我希望看到开始和结束范围是5> 1。 7计数为3,而不是表中的单独行。

我尝试了不同的变量min(start_num),max(end_num),但它给了我整个范围company1 = 1 - 7。

我需要它看起来像这样......

lcn_code    start      end     count
company1       1        1        1 
company1       3        3        1
company1       5        7        3

company2       2        2        1
company2       4        4        1
company2       8        9        2
等等......

当没有顺序中断而不是单个行时,基本上给我一个该范围的总数。

非常新手,所以我需要整个字符串。

1 个答案:

答案 0 :(得分:1)

它有点复杂,希望你能设法简化......

select lcn_code, min(start_num), max(end_num), count(*)
  from (
        select a.*,
               max(bound_break) over(partition by lcn_code
                                         order by end_num
                                     ) rank_num
          from (select a.*, 
                       case 
                       when end_num = prev_num + 1 and
                            end_num = next_num - 1 
                         then null 
                       when end_num = prev_num + 1  
                         then null
                       when end_num = next_num - 1 
                         then end_num
                         else end_num 
                       end as bound_break                             
                from (select a.*, 
                             lag(start_num, 1, null) over(partition by lcn_code order by end_num) as prev_num,
                             lead(start_num, 1, null) over(partition by lcn_code order by end_num) as next_num 
                        from test_data a
                     ) a
               ) a 
        )
group by lcn_code, rank_num
order by lcn_code, rank_num
;