Partial pivot without pivot operator

2019-07-12 05:08发布

问题:

I am looking for a query to partially pivot a table without using the PIVOT operator (old ms-sql server). the table:

id-------item---------rank1---------rank2
231------it1--------- 1 ----------- 1
231------it2-------- 1 ----------- 2 
231------it3--------- 1 ----------- 3
154------it4--------- 3 ----------- 4
154------it2--------- 1 ----------- 2
155------it2--------- 1 ----------- 2
156------it3 -------- 2 ----------- 2
156------it1 -------- 1 ----------- 1

expected result:

id---------item1----item2----item3---item*... 
231 -------it1------it2---------it3 
154--------it2------it4 
155--------it2 
156--------it1------it3

order by rank1 and rank2

I searched on google but the solution I found was too complicated to apply.

回答1:

In SQL Server, you could use row_number to assign a row number for each id group. Then you can use the max(case(... trick to pivot:

select  id
,       max(case when rn = 1 then item end) as item1
,       max(case when rn = 2 then item end) as item2
,       max(case when rn = 3 then item end) as item3
from    (
        select  row_number() over (partition by id
                    order by rank1, rank2) as rn
        ,       *
        from    YourTable
        ) as SubQueryAlias
group by
        id

There is no general solution for N items without using dynamic SQL.