我已经搜索了高低,以获得答案,如果它已经回答了,那么道歉!
我在sql 2005中的查询中得到以下结果:
我在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]
解决方法
您还需要查询中的值字段,以便聚合每个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