sql-server – SQL Server – 将行转置为列

前端之家收集整理的这篇文章主要介绍了sql-server – SQL Server – 将行转置为列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经搜索了高低,以获得答案,如果它已经回答了,那么道歉!
我在sql 2005中的查询中得到以下结果:
  1. ID
  2.  
  3. 1234
  4.  
  5. 1235
  6.  
  7. 1236
  8.  
  9. 1267
  10.  
  11. 1278

我想要的是

  1. column1|column2|column3|column4|column5
  2. ---------------------------------------
  3. 1234 |1235 |1236 |1267 |1278

我不能完全理解枢轴运算符,但看起来它会涉及到它.我现在可以使用只有5行,但奖励是动态的,即可以扩展到x行.

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

  1. DECLARE @id1 int,@id2 int,@id3 int,@id4 int,@id5 int
  2.  
  3. SELECT @id1 = column1,@id2 = column2,@id3 = column3,@id4 = column4,@id5 = column5 FROM [transposed_table]

解决方法

您还需要查询中的值字段,以便聚合每个ID.然后你可以做这样的事情
  1. select [1234],[1235]
  2. from
  3. (
  4. -- replace code below with your query,e.g. select id,value from table
  5. select
  6. id = 1234,value = 1
  7. union
  8. select
  9. id = 1235,value = 2
  10. ) a
  11. pivot
  12. (
  13. avg(value) for id in ([1234],[1235])
  14. ) as pvt

猜你在找的MsSQL相关文章