SQL Server - 将行转置为列

时间:2012-05-22 10:12:31

标签: sql-server sql-server-2005 pivot

我已经高低搜索了这个答案,如果它已经得到答案就道歉了! 我在SQL 2005中的查询中得到以下结果:

ID

1234

1235

1236

1267

1278

我想要的是

column1|column2|column3|column4|column5
---------------------------------------
1234   |1235   |1236   |1267   |1278

我无法完全了解枢轴操作员,但这似乎会涉及到它。我现在可以使用只有5行,但奖励是动态的,即可以扩展到x行。

编辑: 我最终要将每个结果列的值分配给变量,例如

DECLARE @id1 int, @id2 int, @id3 int, @id4 int, @id5 int

SELECT @id1 = column1, @id2 = column2, @id3 = column3, @id4 = column4, 
@id5 = column5 FROM [transposed_table]

3 个答案:

答案 0 :(得分:5)

您还需要查询中的值字段,以便聚合每个ID。然后你可以做这样的事情

select [1234], [1235]
from
(
    -- replace code below with your query, e.g. select id, value from table
    select
    id = 1234,
    value = 1
    union
    select
    id = 1235,
    value = 2
) a
pivot
(
  avg(value) for id in ([1234], [1235])
) as pvt

答案 1 :(得分:2)

我想你会在这个答案中找到一个稍微不同的答案的答案:Generate "scatter plot" result of members against sets from SQL query

答案使用动态SQL。查看mellamokb的答案中的最后一个链接:http://www.sqlfiddle.com/#!3/c136d/14他从行数据中创建列名。

答案 2 :(得分:1)

如果您有一个分组平面数据结构,您希望对其进行分组,例如:

GRP  | ID
---------------
1    | 1234
1    | 1235
1    | 1236
1    | 1267
1    | 1278
2    | 1234
2    | 1235
2    | 1267
2    | 1289

你希望它的组换位看起来像:

GRP | Column 1 | Column 2 | Column 3 | Column 4 | Column 5
-------------------------------------------------------------
1   | 1234     | 1235     | 1236     | 1267     | 1278
2   | 1234     | 1235     | NULL     | 1267     | NULL

您可以使用以下查询完成此操作:

SELECT
    Column1.ID As column1,
    Column2.ID AS column2,
    Column3.ID AS column3,
    Column4.ID AS column4,
    Column5.ID AS column5
FROM
    (SELECT GRP, ID FROM FlatTable WHERE ID = 1234) AS Column1
LEFT OUTER JOIN
    (SELECT GRP, ID FROM FlatTable WHERE ID = 1235) AS Column2
ON Column1.GRP = Column2.GRP
LEFT OUTER JOIN
    (SELECT GRP, ID FROM FlatTable WHERE ID = 1236) AS Column3
ON Column1.GRP = Column3.GRP
LEFT OUTER JOIN
    (SELECT GRP, ID FROM FlatTable WHERE ID = 1267) AS Column4
ON Column1.GRP = Column4.GRP
LEFT OUTER JOIN
    (SELECT GRP, ID FROM FlatTable WHERE ID = 1278) AS Column5
ON Column1.GRP = Column5.GRP

(1)这假设你提前知道你想要哪些列 - 注意我故意遗漏了这个例子中的ID = 1289

(2)这基本上使用一堆左外连接一次追加1列,从而创建转置。左外连接(而不是内连接)允许某些列为空,如果它们没有来自平面表的相应值,而不影响任何后续列。