这个格式怎么变的来着?不记得了。

geniuswjt 2012-01-12 11:47:57
data:
1
2
3
4
6
7
9
11
12
13
……
result:
1-4
6-7
9-9
11-13
……

也就是判断连续的。记得之前看过水哥还是谁的操作来着,有知情者贴下么。
...全文
173 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2012-01-12
  • 打赏
  • 举报
回复

declare @T table (data int)
insert into @T
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 6 union all
select 7 union all
select 9 union all
select 11 union all
select 12 union all
select 13

select min(data),max(data) from
(
select *,rid=(select count(1)+1 from @t where data<a.data) from @t a
) b group by data-rid
/*
1 4
6 7
9 9
11 13
*/

SQL SERVER 2000没有row_number的话,这样就可以了,不需要用master..spt_values。
叶子 2012-01-12
  • 打赏
  • 举报
回复
数据不大的话,辅助master..spt_values应该也可以吧...
水族杰纶 2012-01-12
  • 打赏
  • 举报
回复
技术内幕-T-SQL查询之孤岛和间断
256页
中国风 2012-01-12
  • 打赏
  • 举报
回复
use Tempdb
go
--> -->

if not object_id(N'Tempdb..#1') is null
drop table #1
Go
Create table #1([data] int)
Insert #1
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 6 union all
select 7 union all
select 9 union all
select 11 union all
select 12 union all
select 13
Go
SELECT
RTRIM(MIN(data))+'-'+RTRIM(MAX(Data)) AS Data
FROM (Select *,ROW_NUMBER()OVER(ORDER BY data)-[data] AS rn from #1)t
GROUP BY rn
ORDER BY MIN(data)

/*
1-4
6-7
9-9
11-13
*/
百年树人 2012-01-12
  • 打赏
  • 举报
回复
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([data] int)
insert [tb]
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 6 union all
select 7 union all
select 9 union all
select 11 union all
select 12 union all
select 13

select a.data,b.data
from
(
select rn=row_number() over(order by getdate()),*
from [tb] t where not exists(select 1 from tb where data=t.data-1)
) a
join
(
select rn=row_number() over(order by getdate()),*
from [tb] t where not exists(select 1 from tb where data=t.data+1)
) b
on a.rn=b.rn


--测试结果:
/*
data data
----------- -----------
1 4
6 7
9 9
11 13

(4 行受影响)
*/
小和桑 2012-01-12
  • 打赏
  • 举报
回复


坐等知情者
geniuswjt 2012-01-12
  • 打赏
  • 举报
回复
嗯,取差值group by的比较讨巧。
有种意识的体现的感觉,不错,结贴。
勿勿 2012-01-12
  • 打赏
  • 举报
回复
declare @T table (data int)
insert into @T
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 6 union all
select 7 union all
select 9 union all
select 11 union all
select 12 union all
select 14 union all
select 15 union all
select 111 union all
select 112 union all
select 113 union all
select 114
select cast(MIN(data)as varchar(50))+'-'+cast(MAX(data) as varchar(50)) from( select data ,rn=ROW_NUMBER()over( order by data)-data from @T)s
group by rn
order by MIN(data)



(15 行受影响)

-----------------------------------------------------------------------------------------------------
1-4
6-7
9-9
11-12
14-15
111-114

(6 行受影响)

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧