2014-09-26 81 views
2

这是我查询过表:的Oracle SQL开始范围结束范围与数量

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 

正如你可以看到,最上面一行start_num可END_NUM是1 & 1所以它的计数1,但然后是在company1下的一个序列中断,他们的下一个数字是3.所以我不想在company1下报告'2'。这一点我可以做(只)。

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

我试过分钟(START_NUM)不同的变化,最大(END_NUM),但它给了我所有的整个范围内公司1 = 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 

等等...

基本上给我这个范围的总数时,有没有sequense休息,而不是单独的行。

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

+0

如果我没有记错,有让你从当前访问查询以下/前行的路,但我不记得语法。你需要查看它然后做这件事会容易得多 – 2014-09-26 13:13:49

+0

另一种方法,你可以做一个PL/SQL块,并跟踪最后一行 – 2014-09-26 13:15:46

回答

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 
; 
+1

哇谢谢你,它完美的工作,难怪我没有得到它对我自己。唯一的另一件事我现在需要加入另一个文件来获得另一个字段,但我不知道在哪里添加加入文件在上面的脚本? – 2014-09-26 14:09:44

+0

其实我已经解决了!非常感谢你的帮助! – 2014-09-26 14:13:49

+0

没问题。请排列我的答案,如果它的工作:-) – Rusty 2014-09-26 14:19:56