我有一个详细信息表,可以通过以下内容进行描述:
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)
全选产生以下内容:
我想将列数据转置为行,以产生以下输出:
谢谢。
答案 0 :(得分:4)
您在这里。只需在子查询中选择第一个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;
答案 1 :(得分:1)
这应该有效:
select HeaderId
, [0] as ChannelId0
, [1] as ChannelId1
, [2] as ChannelId2
, [3] as ChannelId3
, [4] as ChannelId4
from
(
select HeaderId, ChannelId,Value
from #Details
) x
pivot
(
max(Value)
for ChannelId in([0],[1],[2], [3],[4],[5])
)p