我有这样的数据:
row_id type value
1 a 1
2 a 2
3 a 3
4 a 5 --note that type a, value 4 is missing
5 a 6
6 a 7
7 b 1
8 b 2
9 b 3
10 b 4
11 b 5 --note that type b is missing no values from 1 to 5
12 c 1
13 c 3 --note that type c, value 2 is missing我希望为每个type中的每个连续“运行”找到最小值和最大值。也就是说,我想回去
row_id type group_num min_value max_value
1 a 1 1 3
2 a 2 5 7
3 b 1 1 5
4 c 1 1 1
5 c 2 3 3我是一个相当有经验的SQL用户,但我从未解决过这个问题。显然,我知道如何获得每个type的总体最小值和最大值,使用GROUP、MIN和MAX,但是对于这些局部极小值和最大值,我实在是不知所措。我在其他问题上没有发现任何能回答我问题的东西。
我在Oracle 11g中使用PLSQL Developer。谢谢!
发布于 2014-11-14 00:24:44
这是一个空隙和岛屿问题。您可以使用解析函数效应/技巧查找每种类型的连续值链:
select type,
min(value) as min_value,
max(value) as max_value
from (
select type, value,
dense_rank() over (partition by type order by value)
- dense_rank() over (partition by null order by value) as chain
from your_table
)
group by type, chain
order by type, min(value);内部查询使用类型内和整个结果集中的值排序之间的差异来创建“链”号。外部查询仅用于分组。
SQL Fiddle包括内部查询的结果。
发布于 2014-11-14 00:34:24
这是实现所需结果的一种方法:
with step_1 as (
select w.type,
w.value,
w.value - row_number() over (partition by w.type order by w.row_id) as grp
from window_test w
), step_2 as (
select x.type,
x.value,
dense_rank() over (partition by x.type order by x.grp) as grp
from step_1 x
)
select rank() over (order by y.type, y.grp) as row_id,
y.type,
y.grp as group_num,
min(y.value) as min_val,
max(y.value) as max_val
from step_2 y
group by y.type, y.grp
order by 1;https://stackoverflow.com/questions/26920248
复制相似问题