SQL Transpose Column?



我正试图用旧表中的数据创建一个新表。我想从一个大约有5000个值的表中提取一列,并将这些值中的每一个作为新表中的一列。然后我想把每一行的数据输入到列中。我想这将作为MSSMS中的一个查询来完成,但我不确定如何完成。

我不知道如何在这里做一张桌子,但基本上这就是我想做的——

Table 1:
       Col1    Col2    Col3
Row1    a      hello   world
Row2    b      why     ok
Row3    c      the     banana
Row4    d      lion    roar
Table 2:
        a      b      c       d
Row1  hello   why    the     lion
Row2  world   ok     banana  roar

您可以使用透视图和并集来填充表。以下内容应该有效:

**更新以便对表中的5000列执行此操作,然后可以将游标与动态sql一起使用。

游标由sys.columns中表中的所有列填充。然后它遍历每一列的动态sql。

动态sql执行透视,并使用光标传递的当前列名更新新表。

Declare @sql varchar(4000),
        @Column varchar(200)
Declare curColumns cursor fast_forward for 
Select name from sys.columns where object_id = OBJECT_ID('Table1')
Open curColumns
Fetch next from curColumns into @Column
While @@FETCH_STATUS = 0
begin
Set @sql = 
'Insert into Table2
Select [a], [b], [c]
from
(select col1, ' + @Column + '
from Table1 ) p
Pivot
(max(col2) for col1 in (a,b,c)
) as pvt'
exec @sql
Fetch next from curColumns into @Column
end
Close curColumns
Deallocate curColumns

最新更新