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语句来返回表中的所有行作为一行,而不是表中的每一行数据的一列?
2 个解决方案
#1
1
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
#2
3
you are looking for a pivot : http://msdn.microsoft.com/en-us/library/ms177410.aspx
您正在寻找一个pivot: http://msdn.microsoft.com/en-us/library/ms177410.aspx。
#1
1
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
#2
3
you are looking for a pivot : http://msdn.microsoft.com/en-us/library/ms177410.aspx
您正在寻找一个pivot: http://msdn.microsoft.com/en-us/library/ms177410.aspx。