sql server如何通过pivot对数据进行行列转换(进阶)
时间:2021-07-01 10:21:17
帮助过:30人阅读
说明: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
脚本运行结果:
【转载请注明博文来源:https://www.cnblogs.com/zhang502219048/p/13173228.html】
sql server如何通过pivot对数据进行行列转换(进阶)
标签:sele 编程 The loading 目标 serve htm info mamicode