选择列的两个字符值之间的行

时间:2016-07-15 01:15:22

标签: sql oracle

我有一张表格如下所示:

S.No   | Action
1      |   New
2      |   Dependent
3      |   Dependent
4      |   Dependent
5      |   New
6      |   Dependent
7      |   Dependent
8      |   New
9      |   Dependent
10     |   Dependent

我这里想要选择Action列中前两个'New'值之间的行,包括带有'New'操作的第一行。像[新的,新的]

例如: 在这种情况下,我想选择行1,2,3,4。

请让我知道如何做到这一点。

2 个答案:

答案 0 :(得分:5)

嗯。让我们计算New作为值显示的累计次数并使用:

select t.*
from (select t.*,
             sum(case when action = 'New' then 1 else 0 end) over (order by s_no) as cume_new
      from t
     ) t
where cume_new = 1;

答案 1 :(得分:0)

你可以用分析函数做一些魔术 1选择一组新动作,以获得最小和最大s_no 2选择2行的引线 3选择在2 sno(最小和最大)之间获取

with t as (
select 1 sno, 'New' action from dual union
select 2,'Dependent' from dual union
select 3,'Dependent' from dual union
select 4,'Dependent' from dual union
select 5,'New' from dual union
select 6,'Dependent' from dual union
select 7,'Dependent' from dual union
select 8,'New' from dual union
select 9,'Dependent' from dual union
select 10,'Dependent' from dual
)
select * 
  from (select * 
          from (select sno, lead(sno) over (order by sno) a 
                  from ( select row_number() over (partition by action order by Sno) t,
                                t.sno
                           from t
                          where t.action = 'New'
                        ) a 
                 where t <=2 ) 
         where a is not null) a, t 
 where t.sno >= a.sno and t.sno < a.a