在动态范围内查找多个最小值和最大值

时间:2013-12-11 11:21:45

标签: sql sql-server tsql

我得到的结果如图所示。

我得到2个值范围

1)从79996到80000

2)从001001到001003

所以,我想要2个最小值79996和001001以及2个最大值80000和001003。

值或范围不固定,可以有超过1个范围。

有可能!!!!

请帮忙......

enter image description here

1 个答案:

答案 0 :(得分:1)

此查询将仅选择连续范围的边界(连续整数,您应该在使用之前将char类型列转换为整数):

select distinct tr_no,
case 
when left_ind = 'gap' and right_ind = 'seq' then 'RANGE_MIN'
when left_ind = 'seq' and right_ind = 'gap' then 'RANGE_MAX'
else 'MIN-MAX' end as bound_type
from
(
select job_no, tr_no,
case when abs(tr_no - PREV_TR) = 1 then 'seq' else 'gap' as left_ind,
case when abs(NEXT_TR - tr_no) = 1 then 'seq' else 'gap' as right_ind
from 
(
select job_no, tr_no, 
LEAD(tr_no) over (order by tr_no) as NEXT_TR,
LAG(tr_no) over (order by tr_no) as PREV_TR
from mytable
) m1
) m2
where left_ind = 'gap' or right_ind = 'gap'