给定一个包含2列的表:table_id
和marker
。
我想找到行之前行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
答案 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