Perhaps you can work out the details on your own based on this sample code.This will take the first Amts for each Code in order of Amt desc and assign them the Amt1-Amt5 columns:declare @t table (Code int, Amt int)insert @tselect 101, 9000 union allselect 101, 3000 union allselect 101, 4000 union allselect 101, 2000 union allselect 101, 8000 union allselect 102, 1000 union allselect 102, 2000 union allselect 102, 4000 union allselect 102, 3500 union allselect 102, 1100 union allselect 103, 6000 union allselect 103, 5000 union allselect 103, 1000 union allselect 103, 1100 union allselect 103, 2900select code ,amt1 = max(case when rn = 1 then amt end) ,amt2 = max(case when rn = 2 then amt end) ,amt3 = max(case when rn = 3 then amt end) ,amt4 = max(case when rn = 4 then amt end) ,amt5 = max(case when rn = 5 then amt end)from (select Code, Amt, row_number() over (partition by code order by Amt desc) rn from @t) dwhere rn < 6group by codeoutput:code amt1 amt2 amt3 amt4 amt5----------- ----------- ----------- ----------- ----------- -----------101 9000 8000 4000 3000 2000102 4000 3500 2000 1100 1000103 6000 5000 2900 1100 1000
Be One with the OptimizerTG