我有一个这样的专栏:
ID
--------
1
2
3
4
5
7
10
我想得到以下结果集:
ID
--------
1-5
7
10
有没有办法仅使用(Oracle)SQL 来实现这一点?
是的:
select (case when min(id) < max(id)
then cast(min(id) as varchar2(255)) || '-' || cast(max(id) as varchar2(255))
else cast(min(id) as varchar2(255))
end)
from (select id, id - rownum as grp
from t
order by id
) t
group by grp
order by min(id);
这是一个演示它的 SQL Fiddle。
查询背后的想法是rownum
从一个数字序列中减去一个常数。您可以使用常量进行分组。
自我加入是必要的......我认为这会奏效
Select a.id, b.id
From table a -- to get beginning of each range
Join table b -- to get end of each range
On b.id >= a.Id -- guarantees that b is after a
And Not exists (Select * From table m -- this guarantees all values between
where id Between a.id+1 and b.id
And Not exists(Select * From table
Where id = m.id-1))
And Not exists (Select * From table -- this guarantees that table a is start
Where id = a.id -1)
And Not exists (Select * From table -- this guarantees that table b is end
Where id = b.id + 1)