Dynamic Pivot Needed with Row_Number()

后端 未结 1 1207
星月不相逢
星月不相逢 2020-12-04 01:21

I am using Microsoft SQL Server Management Studio 2008.

I have data that looks like this:

Client ID        Value
-------------------------------
123         


        
相关标签:
1条回答
  • 2020-12-04 01:48

    with using a cte, with row_number you can achieve the result:

    Your Schema:

    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');
    

    The query:

    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
    

    The Result:

    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
    
    0 讨论(0)
提交回复
热议问题