MS SQL Server。将数据列转置为数据行

时间:2018-11-05 14:25:17

标签: sql sql-server tsql pivot

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

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

谢谢。

2 个答案:

答案 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;

以下结果: enter image description here

答案 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