如何从多列中选择最低的3个数字?
id num1 num2 num3 num4 num5
----------- ----------- ----------- ----------- ----------- -----------
1 1 6 5 1 2
2 6 2 2 3 2
3 2 1 2 1 5
4 4 1 1 5 7
5 5 1 4 7 8
例如
(来自id 1的最低2个值)> ((来自id 5的最低2个值)
答案 0 :(得分:3)
一种方法使用cross apply
:
select t.id, v.num
from t cross apply
(select top 3 num
from (values (num1), (num2), (num3), (num4), (num5)) v(num)
order by num asc
) v;
如果你想让它们在同一行,那么重新转动:
select t.id, v.*
from t cross apply
(select max(case when seqnum = 1 then num end) as num1,
max(case when seqnum = 2 then num end) as num2,
max(case when seqnum = 3 then num end) as num3
from (select num, row_number() over (order by num) as seqnum
from (values (num1), (num2), (num3), (num4), (num5)) v(num)
) v
) v;
答案 1 :(得分:1)
执行order by desc
并选择top
行,例如
select top 3 num1, num2, num3
from tbl1
order by num1 desc, num2 desc, num3 desc