大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说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(N"2020-01", N"业务员1", N"100") , (N"2020-01", N"业务员2", N"200") , (N"2020-02", N"业务员2", N"300") , (N"2020-02", N"业务员3", N"400") , (N"2020-03", N"业务员4", N"500") , (N"2020-03", N"业务员5", N"600") , (N"2020-04", N"业务员1", N"700") , (N"2020-04", N"业务员3", N"800") --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
代码100分
脚本运行结果:
【转载请注明博文来源:https://www.cnblogs.com/zhang502219048/p/13173228.html】
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/7770.html