用事務實現行轉列

來源:互聯網
上載者:User
if object_id('Tempdb..#Roy') is not nulldrop table #Roycreate table  #Roy (a int,b varchar(10),c int,d int)insert #Royselect 1,    '小李', 1,    2 union allselect 2,    '小王', 4,    5  union all select 1,    '小李', 3,    4 union allselect 2,    '小王', 6,    7 union allselect 1,    '小李', 5,    6 union allselect 2,    '小王', 8,    9sql2000實現:begin tran if object_id('tempdb..#roy2') is not nulldrop table #roy2select a,b,num,id=identity(int,1,1) into #roy2--產生暫存資料表from (select a,b,c as num from #Royunion allselect a,b,d from #Roy)a order by b,num asc--排序方式--動態查詢declare @s nvarchar(1000),@i intselect top 1 @i=count(1),@s='' from #roy2 group by a order by count(1) descwhile @i>0select @s=',[Col'+rtrim(@i)+']=max(case when ID='+rtrim(@i)+' then rtrim(num) else '''' end)'+@s,@i=@i-1exec('select a,b'+@s+ 'from (select a,b,num,ID=(select count(1) from #roy2 where a=a.a and ID<=a.ID) from #roy2 a)T group by a,b')drop table #roy2rollback  transql2005:begin tran--開始事務declare @i int,@s nvarchar(1000),@Col nvarchar(1000)select top 1 @i=count(1),@s='',@Col=''  from #roy unpivot (Num for Col in(c,d))b  group by a order by count(1) descwhile @i>0select @s=','+quotename(@i)+@s,@Col=',[Col'+rtrim(@i)+']='+quotename(@i)+@Col,@i=@i-1set @s=stuff(@s,1,1,'')exec('with CTEas(select a,b,num,row=row_number()over(partition by a order by num)from #royunpivot(Num for Col in(c,d))b)select a,b'+@Col+' from CTE pivot (max(num) for row in('+@s+'))b')rollback tran/*a           b          Col1        Col2        Col3        Col4        Col5        Col6----------- ---------- ----------- ----------- ----------- ----------- ----------- -----------1           小李         1           2           3           4           5           62           小王         4           5           6           7           8           9(2 行受影響)*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.