Here's one way:;with test (name, value)as( select 'a', 1 union all select 'a', 4 union all select 'b', 2 union all select 'b', 6 union all select 'c', 1)select name ,[1] as Max1 ,[2] as Max2from ( select * from ( select name , value , rn = row_number() over (partition by name order by value desc) from test ) d where rn < 3 ) d (name, value, rn)pivot ( max([value]) for [rn] in ([1],[2]) ) poutput:name Max1 Max2---- ----------- -----------a 4 1b 6 2c 1 NULL
Be One with the OptimizerTG