gpt4 book ai didi

sql - 微软 SQL 服务器。将数据列转置为数据行

转载 作者:行者123 更新时间:2023-12-02 09:10:16 25 4
gpt4 key购买 nike

我有一个详细信息表,可以通过以下方式进行描述:

Create table #Details (
Id int identity,
HeaderId int,
ChannelId int,
Value float
)

我们插入一些种子数据:

insert into #Details (HeaderId, ChannelId, Value) values(1, 0, 1019.51)
insert into #Details (HeaderId, ChannelId, Value) values(1, 1, 20.1)
insert into #Details (HeaderId, ChannelId, Value) values(1, 2, 21.2)
insert into #Details (HeaderId, ChannelId, Value) values(1, 3, 22.3)
insert into #Details (HeaderId, ChannelId, Value) values(1, 4, 23.4)

insert into #Details (HeaderId, ChannelId, Value) values(2, 0, 1020.62)
insert into #Details (HeaderId, ChannelId, Value) values(2, 1, 26.1)
insert into #Details (HeaderId, ChannelId, Value) values(2, 2, 27.2)
insert into #Details (HeaderId, ChannelId, Value) values(2, 3, 28.3)
insert into #Details (HeaderId, ChannelId, Value) values(2, 4, 29.4)

全选会产生以下结果:

enter image description here

我想将列数据转置为行,以产生以下输出:

enter image description here

提前致谢。

最佳答案

给你。只需在子查询中选择第一个 HeaderId,value, ChannelId,然后进行透视即可。

DECLARE @tbl TABLE (Id int identity,
HeaderId int,
ChannelId int,
Value float)

insert into @tbl (HeaderId, ChannelId, Value) values(1, 0, 1019.51)
insert into @tbl (HeaderId, ChannelId, Value) values(1, 1, 20.1)
insert into @tbl (HeaderId, ChannelId, Value) values(1, 2, 21.2)
insert into @tbl (HeaderId, ChannelId, Value) values(1, 3, 22.3)
insert into @tbl (HeaderId, ChannelId, Value) values(1, 4, 23.4)

insert into @tbl (HeaderId, ChannelId, Value) values(2, 0, 1020.62)
insert into @tbl (HeaderId, ChannelId, Value) values(2, 1, 26.1)
insert into @tbl (HeaderId, ChannelId, Value) values(2, 2, 27.2)
insert into @tbl (HeaderId, ChannelId, Value) values(2, 3, 28.3)
insert into @tbl (HeaderId, ChannelId, Value) values(2, 4, 29.4)

SELECT *
FROM
(
SELECT HeaderId,value, ChannelId
FROM
@tbl
)T
PIVOT
(
SUM(value)

FOR ChannelId IN ([0],[1], [2], [3], [4]

)
) AS PivotTable;

结果如下: enter image description here

关于sql - 微软 SQL 服务器。将数据列转置为数据行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53156307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com