复杂SQL查询在包含特定文本的行之前查找行

时间:2014-07-14 14:31:12

标签: sql oracle

给定一个包含2列的表:table_idmarker

我想找到行之前marker ='GeneticMutant'

这是什么类型的查询,我是Oracle SQL Developer的新手。谢谢!

-------------------------
`table_id`   |   `marker`
1000         |   ccgcccgccc
2000         |   GeneticMutant
3000         |   bbcbbccgggcddd
4000         |   cccgccgdddcccc
5000         |   GeneticMutant
6000         |   cgcgcbabsshdhd
7000         |   GeneticMutant
8000         |   cgcgcgcgcbbcbcc
9000         |   GeneticMutant

所需输出

1000,4000,6000,8000

2 个答案:

答案 0 :(得分:2)

Analityc函数LAG可帮助您阅读上一行:

with t as (
  select 1 id, 'NoGeneticMutant' marker from dual union all
  select 2, 'HalfGeneticMutant' marker from dual union all
  select 3, 'GeneticMutant' marker from dual union all
  select 4, 'AnotherGeneticMutant' marker from dual union all
  select 5, 'DifferentGeneticMutant' marker from dual union all
  select 6, 'GeneticMutant' marker from dual union all
  select 7, 'AmazingGeneticMutant' marker from dual union all
  select 8, 'UltimateGeneticMutant' marker from dual union all
  select 9, 'GeneticMutant' marker from dual
)
select t.*
  from t
     , (select id
             , marker
             , lag(marker) OVER(order by id) prev_marker 
          from t
       ) t1
 where t.marker = t1.prev_marker
   and t1.marker = 'GeneticMutant'

ID  MARKER
2   HalfGeneticMutant
5   DifferentGeneticMutant
8   UltimateGeneticMutant

删除WITH子句并将"t"替换为您的表格。您还必须指定订单,我使用ORDER BY ID您可以拥有自己的订单字段

答案 1 :(得分:0)

这可以通过LAG()函数完成,该函数提供对多行的访问。 http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions070.htm

这是上面链接中的示例,其中显示了如何访问上一行。当然,必须有一个ORDER BY子句才能知道前一行是什么。

SELECT last_name, hire_date, salary,
   LAG(salary, 1, 0) OVER (ORDER BY hire_date) AS prev_sal
   FROM employees
   WHERE job_id = 'PU_CLERK';

LAST_NAME                 HIRE_DATE     SALARY   PREV_SAL
------------------------- --------- ---------- ----------
Khoo                      18-MAY-95       3100          0
Tobias                    24-JUL-97       2800       3100
Baida                     24-DEC-97       2900       2800
Himuro                    15-NOV-98       2600       2900
Colmenares                10-AUG-99       2500       2600