分享

一个简单的交叉报表_行转列

 新进小设计 2022-03-30
--行转列小实例
--创建测试表
if object_id(N'test', N'U') is not null
  drop table test
go
with PivotTable as
(
  select 'xxx' as czy, '点赞' as czlx, 2 as num
  union all
  select 'xxx', '浏览' as czlx, 14 as num
  union all
  select 'yyy', '浏览' as czlx, 10 as num
  union all
  select 'zzz', '浏览', 30
  union all
  select 'zzz', '点赞', 3 
)
select * into test from PivotTable
go
--创建存储过程
if exists(select name from sysobjects where name = 'usp_GetPivotInfo')
    drop proc usp_GetPivotInfo
go

create proc usp_GetPivotInfo
as
declare @czlx varchar(500),
        @SQL varchar(2000)        
select @czlx = stuff((select distinct ',[' + czlx + ']'  from test for xml path ('')),1,1,'')
--select @czlx
set @SQL = 'select czy, {#} from test pivot(sum(num) for czlx in ({#})) as T';
set @SQL = replace(@SQL, '{#}', @czlx);
exec(@SQL);
go

exec usp_GetPivotInfo ;

交叉前

 

 

交叉后

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多