sql >> データベース >  >> RDS >> Sqlserver

Row_Number()で必要な動的ピボット

    cteを使用して 、row_numberを使用 あなたは結果を達成することができます:

    スキーマ:

    create table your_table([Client ID] int ,Value varchar(50));
    insert into your_table values
    (12345,            'Did Not Meet'),
    (12345,            'Did Not Meet'),
    (12345,            'Partially Met'),
    (12346,            'Partially Met'),
    (12346,            'Partially Met'),
    (12346,            'Partially Met'),
    (12347,            'Partially Met'),
    (12347,            'Partially Met'),
    (12347,            'Did Not Meet'),
    (12347,            'Met');
    

    クエリ:

    with cte as
    (
     select [Client ID] ci,value,
            row_number() over(partition by [Client ID] order by value) as rn
     from your_table
    )
    select distinct ci as [Client ID],
           (select ct.value from cte ct where ct.ci=cte.ci and ct.rn=1) value1,
           (select ct.value from cte ct where ct.ci=cte.ci and ct.rn=2) value2,
           (select ct.value from cte ct where ct.ci=cte.ci and ct.rn=3) value3,
           (select ct.value from cte ct where ct.ci=cte.ci and ct.rn=4) value4
    from cte
    

    結果:

    Client ID   value1          value2          value3          value4
    12345       Did Not Meet    Did Not Meet    Partially Met   (null)
    12346       Partially Met   Partially Met   Partially Met   (null)
    12347       Did Not Meet    Met Partially   Met Partially    Met
    



    1. MicrosoftAccessデータベースのSQLServerへの移行

    2. PDO ::ATTR_EMULATE_PREPARESを無効にすると、「不明」の問題が発生します

    3. Django 1.6(南)から1.8にアップグレードしても、ユーザーテーブルの「last_login」は変更されません

    4. UML図を自動的に生成する方法はありますか?