简体   繁体   English

将单列数据转换成多列单行

[英]Single column of data into multiple columns single row

I have a table that has one column. 我有一个只有一列的表。 How do I write a T-SQL statement to return all the rows in the table as one row but a column for each row of data in the table? 如何编写T-SQL语句以将表中的所有行返回为一行,而表中每一行数据则返回一列?

您正在寻找一个枢轴: http : //msdn.microsoft.com/en-us/library/ms177410.aspx

You can do this by building a dynamic sql statement. 您可以通过构建动态sql语句来做到这一点。

-- Test data
declare @T table (F varchar(10))
insert into @T values
('Row 1'),
('Row 2'),
('Row 3'),
('Row 4'),
('Row 5')

-- String to hold dynamic sql
declare @S as varchar(max)
set @S = 'select '

--Build string
select @S = @S + quotename(F, '''') + ',' 
from @T
set @S = left(@S, len(@s)-1)

--Execute sql 
exec (@S)

Result 结果

----- ----- ----- ----- -----
Row 1 Row 2 Row 3 Row 4 Row 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM