sql server如何通过pivot对数据进行行列转换(进阶)

脚本:

/*
说明:sql server如何通过pivot对数据进行行列转换(进阶),用于员工业绩按月龙虎排行榜、客户销售金额按月排行榜等
脚本来源:https://www.cnblogs.com/zhang502219048/p/13173228.html
作者:zhang502219048
作者微信公众号:SQL数据库编程(微信号zhang502219048)
*/

declare @n int = 2

create table #t1
(
    [月份] nvarchar(50),
    [业务员] nvarchar(50),
    [金额] int
)
insert into #t1
values(N2020-01, N业务员1, N100)
    , (N2020-01, N业务员2, N200)
    , (N2020-02, N业务员2, N300)
    , (N2020-02, N业务员3, N400)
    , (N2020-03, N业务员4, N500)
    , (N2020-03, N业务员5, N600)
    , (N2020-04, N业务员1, N700)
    , (N2020-04, N业务员3, N800)

--select * from #t1

select [行序号] = row_number() over(partition by [月份] order by [金额] desc)
     , *
into #t2
from #t1

--select * from #t2

create table #t3
(
    [列序号] int,
    [行序号] int,
    [月份] nvarchar(50),
    [结果] nvarchar(50),
    [类型] nvarchar(50)
)

insert into #t3
select [列序号] = 1, [行序号], [月份], [结果] = [业务员], [类型] = [月份] + N-业务员
from #t2

insert into #t3
select [列序号] = 2, [行序号], [月份], [结果] = [金额], [类型] = [月份] + N-金额
from #t2

--select * from #t3

declare @sqlIn nvarchar(max) = ‘‘
select @sqlIn = @sqlIn + case when @sqlIn <> ‘‘ then , else ‘‘ end + [ + [类型] + ] 
from (select distinct [列序号], [月份], [类型] from #t3) a
order by [月份], [列序号]
--select @sqlIn

--行列转换后的目标数据
declare @sql nvarchar(max) = 
select top  + cast(@n as nvarchar(10)) + @sqlIn + 
from (select [行序号], [结果], [类型] from #t3) D
pivot(max([结果]) for [类型] in ( + @sqlIn + )) Q
order by [行序号]

exec(@sql)

drop table #t1, #t2, #t3

脚本运行结果:
sql server如何通过pivot对数据进行行列转换(进阶)

【转载请注明博文来源:https://www.cnblogs.com/zhang502219048/p/13173228.html】

sql server如何通过pivot对数据进行行列转换(进阶)

上一篇:h5分享功能[通过复制网页链接分享]


下一篇:CSS布局学习总结