如何轮换 SQL Server 2005 中的查询结果? [英] How can I rotate the results of a query in SQL Server 2005?
问题描述
我希望能够轮换 SQL 查询的结果,以便结果不是在一系列行中返回,而是作为具有多列的单行返回.例如下表.
I would like to be able to rotate the results of a SQL Query so that instead of the results being returned in a series of rows the results are returned as a single row with multiple columns. For example with the following table.
Create Table TestData
(
things varchar(25)
)
Insert into TestData values ('Thing1')
Insert into TestData values ('Thing2')
Insert into TestData values ('Thing3')
Insert into TestData values ('Thing4')
我想要一个像 Select things from TestData
返回类似的东西Thing1 Thing2 Thing3 Thing4
to return something like Thing1 Thing2 Thing3 Thing4
而不是
- 事情 1
- 事情 2
- 事情 3
- 事情 4
预先感谢您的帮助.
更新:
在看到 Gratzy 建议使用 Pivot 后,我发现我可以像这样向表中添加标识列来获得所需的结果.
After seeing the recommendation by Gratzy to use Pivot I found I can get the desired result by adding an identity column to the table like so.
Create Table TestData
(
id int identity,
things varchar(25)
)
然后运行以下.
SELECT *
FROM TestData
PIVOT
(
MAX(Things)
FOR [ID] IN ([1],[2],[3],[4])
)
AS Result
推荐答案
可以试试PIVOT
http://msdn.microsoft.com/en-us/library/ms177410.aspx
这篇关于如何轮换 SQL Server 2005 中的查询结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!