Sql Server 数据纵列转横列的例子

发布时间:2020-01-07编辑:脚本学堂
本文分享一例sql server中数据纵列转横列的代码,学习下sql server中数据列转换的实现方法,有需要的朋友参考下。

sql server数据列转换的例子,将纵列转换为横列。

代码:
 

复制代码 代码示例:

-- 数据列的转换
declare @fromDate datetime, @dueDate datetime
select @fromDate = '2013-09-01', @dueDate='2013-09-16'

select top 100 a.ProductId, convert(nvarchar(10), b.OrderDate, 20) as OrderDate, count(*) as ProductCount
into #
from Sales.SalesOrderDetail a
inner join Sales.SalesOrderHeader b on a.SalesOrderId = b.SalesOrderId
where b.OrderDate >= @fromDate and b.OrderDate <= @dueDate
group by a.ProductId, b.OrderDate
order by a.ProductId, b.OrderDate

insert into #
select ProductId, 'TOTAL', sum(ProductCount)
from #
group by ProductId

declare @sql varchar(8000)
set @sql = 'select ProductId '

select @sql = @sql + ', sum(case OrderDate when ''' + OrderDate + ''' then ProductCount else 0 end) as [' + OrderDate + ']'
from #
group by OrderDate;

set @sql = @sql + ' from # group by ProductId '

-- source
select * from # order by ProductId, OrderDate

-- transposed
exec(@sql)

drop table #