我想提出一个关于oracle / sql查询的问题。
我有一些数据如下,
Column1
25
20
15
12
11
10
我想得到这样的结果,
Column1
5 (25-20)
5 (20-15)
3 (15-12)
1 (12-11)
1 (11-10)
我正在使用游标来获取这些结果。但是,我真的不想使用游标,因为我有很多行要计算。是否有任何函数可以在Oracle / Sql中获得结果,例如“Case When,Roll Up”。
答案 0 :(得分:9)
这些函数是lag()和lead(),请参见此处 - http://www.orafaq.com/node/55
它们可以像这样使用 -
select
value - prev_value as diff,
'(' || to_char(value) || ' - ' || to_char(prev_value) || ')' as expression
from (
select value, idx,
lag(value) over (order by idx) as next_value,
lead(value) over (order by idx) as prev_value
from(
select 25 as value, 1 as idx from dual
union all select 20 as value, 2 as idx from dual
union all select 15 as value, 3 as idx from dual
union all select 12 as value, 4 as idx from dual
union all select 11 as value, 5 as idx from dual
union all select 10 as value, 6 as idx from dual
)
) where prev_value is not null