如何寻找最小/大值!
表格如下:
id num
01 1
02 3
03 3
04 5
05 18
06 99
.. ..
num有可能重复,id最大为10。
求
最小/最大 1/99
次小/次大 3/18
第三小/第三大 5
第四小/第四大
第五小/第五大
------解决方案----------------------第5小(大)
select top 1 * from (select top 5 * from 表格 ORDER BY num (DESC)) m
。。。1\2\..同理
------解决方案--------------------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