|
发表于 2020-11-27 23:15:01
|
显示全部楼层
if object_id('ta')>0 drop table ta
create table ta (id varchar(8),num int)
insert into ta select '01', 1
insert into ta select '02', 3
insert into ta select '03', 2
insert into ta select '04', 5
insert into ta select '05', 18
insert into ta select '06', 99
insert into ta select '07', 19
insert into ta select '08', 29
insert into ta select '09', 39
insert into ta select '10', 49
insert into #t1 select * from ta
create table #ta(string1 varchar(20),string2 varchar(20))
declare @max int --始终取得最大值
declare @min int --始终取得最小值
declare @i int --次数
set @max=(select max(num) from #t1)
set @min=(select min(num) from #t1)
set @i=0
select * from #t1 where num in(select max(num) from #t1) union all select * from #t1 where num in(select min(num) from #t1)
while @@rowcount>0
begin
set @i=@i+1
insert into #ta select '最'+cast(@i as varchar)+'小/最'+cast(@i as varchar)+'大',cast(@min as varchar)+'/'+cast(@max as varchar)
delete from #t1 where id in(select id from #t1 where num in(select max(num) from #t1)) or id in(select id from #t1 where num in(select min(num) from #t1))
set @max=(select max(num) from #t1)
set @min=(select min(num) from #t1)
select * from #t1 where num in(select max(num) from #t1) union all select * from #t1 where num in(select min(num) from #t1)
end
select * from #ta
/*结果
string1 string2
-------------------- --------------------
最1小/最1大 1/99
最2小/最2大 2/49
最3小/最3大 3/39
最4小/最4大 5/29
最5小/最5大 18/19
(5 行受影响)
*/
drop table ta |
|