行表示前3个最大值IN TABLE

时间:2017-09-11 12:29:48

标签: sql sql-server sql-server-2012

问题输入:

c1  c2  c3  c4  c5  c6
--  --  --  --  --  --
A    1   5  10   7   9
B   11  12  30   5   4
C    5   6   7   2  20
D    3   5   4   1   2

预期产出:

A   C4  C6  C5      
B   C4  C3  C2      
C   C6  C4  C3      
D   C3  C4  C2  

查找每行中的三个最大值。

1 个答案:

答案 0 :(得分:1)

此解决方案首先使用UNPIVOT将列转换为行。

和ROW_NUMBER根据值获取订单号。

然后在该row_number上使用PIVOT来获得前3列。

-- using a table variable to demonstrate
declare @T table (c1 varchar(1), c2 int, c3 int, c4 int, c5 int, c6 int);

-- test data
insert into @T (c1,c2,c3,c4,c5,c6) values
('A', 1, 5, 10, 7, 9),
('B', 11, 12, 30, 5, 4),
('C', 5, 6, 7, 2, 20),
('D', 3, 5, 4, 1, 2);

select c1, [1] as Max1, [2] as Max2, [3] as Max3
from
(
    select 
    c1, upper(col) as col, 
    row_number() over (partition by c1 order by val desc, col) as rn
    from @T t
    unpivot (val for col in (c2, c3, c4, c5, c6)) up
) q
pivot (max(col) for rn in ([1],[2],[3])) as p

结果:

c1  Max1 Max2 Max3
A   C4   C6   C5
B   C4   C3   C2
C   C6   C4   C3
D   C3   C4   C2