欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个简单的交叉报表

程序员文章站 2022-07-10 21:12:53
--行转列小实例 --创建测试表 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 ......
--行转列小实例
--创建测试表
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 ;

交叉前

 一个简单的交叉报表

 

交叉后

一个简单的交叉报表