码迷,mamicode.com
首页 > 其他好文 > 详细

一个简单的交叉报表

时间:2020-04-14 22:58:12      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:测试表   union   exec   with   exe   简单   sum   into   get   

--行转列小实例
--创建测试表
if object_id(Ntest, NU) 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 ;

 

一个简单的交叉报表

标签:测试表   union   exec   with   exe   简单   sum   into   get   

原文地址:https://www.cnblogs.com/adsoft/p/12701454.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!