2

PIVOT 演算子 (古い ms-sql サーバー) を使用せずにテーブルを部分的にピボットするクエリを探しています。テーブル:

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

期待される結果:

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

ランク 1 とランク 2 の順序

Google で検索しましたが、見つけた解決策は複雑すぎて適用できませんでした。

4

1 に答える 1

1

SQL Server では、各グループrow_numberに行番号を割り当てるために使用できました。id次に、max(case(...トリックを使用してピボットできます。

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

動的 SQL を使用しないと、N 個の項目に対する一般的な解決策はありません。

于 2012-09-22T09:50:29.973 に答える