如何在SQL Server中为行值创建列值?

时间:2018-01-28 01:33:56

标签: sql-server sql-server-2008 sql-server-2012

如何在SQL Server中为行值创建列值? (SQL Server 2008或SQL Server 2012)?

我正在尝试创建一个将列值推送到行值的Pivot格式。

create table #testpivot 
(
      buyer nvarchar(1000), 
      Amount money, 
      TranscDate datetime 
)
go

insert into #testpivot 
values ('Sam', 100, '2018-01-15 10:19:34.400'),
       ('Sam', 200, '2018-01-15 11:19:34.400'),
       ('Sam', 300, '2018-01-15 21:19:34.400'),
       ('Ed', 100, '2018-01-15 10:19:34.400'),
       ('Ed', 100, '2018-01-16 14:19:34.400'),
       ('Ed', 100, '2018-01-16 08:19:34.400'),
       ('Ed', 100, '2018-01-17 12:19:34.400'),
       ('Ed', 100, '2018-01-17 01:19:34.400')
go

select * from #testpivot
Go

预期结果:

Buyer       01/15/2018   01/16/2018      01/17/2018     TotalAmt
------------------------------------------------------------------
Sam             600        0                0              600                                         
Ed              100        200             200             500

1 个答案:

答案 0 :(得分:2)

首先,阅读{{3}} 对于您的示例,查询看起来像这样

declare  @testpivot table( buyer nvarchar(1000), Amount money, TranscDate datetime )

insert into @testpivot values ('Sam', 100, '2018-01-15 10:19:34.400')
insert into @testpivot values ('Sam', 200, '2018-01-15 11:19:34.400')
insert into @testpivot values ('Sam', 300, '2018-01-15 21:19:34.400')
insert into @testpivot values ('Ed', 100, '2018-01-15 10:19:34.400')
insert into @testpivot values('Ed', 100, '2018-01-16 14:19:34.400')
insert into @testpivot values ('Ed', 100, '2018-01-16 08:19:34.400')
insert into @testpivot values('Ed', 100, '2018-01-17 12:19:34.400')
insert into @testpivot values('Ed', 100, '2018-01-17 01:19:34.400')

;with tbl as(
select buyer,Amount,cast(TranscDate as date) TranscDate,sum(amount) over(partition by buyer) total
from @testpivot
)
select buyer,[2018-01-15],[2018-01-16],[2018-01-17],total
from tbl
pivot (sum(amount) for TranscDate in ([2018-01-15],[2018-01-16],[2018-01-17])
) as pvt

如果您无法使用日期的硬编码列表,则需要动态SQL 来准备和执行查询。