根据唯一ID将行转换为一行

时间:2016-11-17 09:00:09

标签: sql sql-server

.blue {
   outline: yellow dotted thin;
   outline-offset: -2px
}

我有上面的表格,我希望通过使用SQL服务器,如下所示的结果我可以通过使用STUFF()函数将行组合成一行,但我希望格式如下所示任何帮助< / p>

Reason                       |   ID
---------------------------------------
Sales - Agent Attitude       |    2
---------------------------------------
Billing - Process            |    2
---------------------------------------
Technical -  Outages         |   1005
---------------------------------------
Technical -  knowledge       |   1005
---------------------------------------
Others                       |   1005
---------------------------------------

2 个答案:

答案 0 :(得分:0)

尝试以下查询..

            select distinct  
            ID   , [1] as 'Reason 1' , [2] as 'Reason 2' , [3] as 'Reason 3'
            from
            (
              select *, ROW_NUMBER() OVER ( PARTITION  BY id ORDER BY reason DESC ) as RID from #temp
            ) src
            pivot
            (
              max(Reason)
              for rid in ([1], [2],[3])
            ) piv
如果你有任何问题,请告诉我们。或关注

答案 1 :(得分:0)

这是枢纽解决方案:

;with
t as (
    SELECT 'Reason ' + cast(ROW_NUMBER() over (partition by id order by id) as varchar(2)) n, *
    from YourTable
)
select *
FROM t
pivot (min(reason) for n in ([Reason 1],[Reason 2],[Reason 3],[Reason 4],[Reason 5])) p