实现ID大小交替 的SQL!!
表:
---------------------------------
id
1
2
3
4
5
6
---------------------------------
结果集合:
---------------------------------
1
6
2
5
3
4
------解决方案--------------------create table tb(id int)
insert tb
select 1
union select 2
union select 3
union select 4
union select 5
union select 6
select n=identity(int,1,2),* into # from tb
select n=identity(int,2,2),* into #1 from tb order by id desc
select top 6 id from (
select * from #
union
select * from #1) t
drop table #,#1
drop table tb
/* 结果
id
-----------
1
2
3
4
5
6
(6 row(s) affected)
*/
------解决方案--------------------create table tb(id int)
insert tb
select 1
union select 2
union select 3
union select 4
union select 5
union select 6
select id
from
(
select
a=(select count(*) from tb where id <=t1.id ),id
from tb t1
where id in(select top 50 percent id from tb order by id)
union all
select
a=(select count(*) from tb where id> =t2.id),id
from tb t2
where id not in(select top 50 percent id from tb order by id)
) A
order by a,id
/*
id
-----------
1
6
2
5
3
4
*/
drop table tb
------解决方案--------------------declare @a table(id int)
insert @a select 1
union all select 2
union all select 3
union all select 4
union all select 5
union all select 6
union all select 7
select id from(
select top 100 percent id,x=(select count(1) from @a where id <=a.id) from @a a order by x
union all
select top 100 percent id ,x=(select count(1) from @a where id> =a.id) from @a a order by x desc
)aa where x <=ceiling((select count(1) from @a)/2.0) order by x,id