加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 16:24:42 所属栏目:MsSql教程 来源:网络整理
导读:我已经搜索了高低,以获得答案,如果它已经回答了,那么道歉! 我在SQL 2005中的查询中得到以下结果: ID12341235123612671278 我想要的是 column1|column2|column3|column4|column5---------------------------------------1234 |1235 |1236 |1267 |1278 我不能
我已经搜索了高低,以获得答案,如果它已经回答了,那么道歉!
我在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读