A simple cross-report

- row transfer columns small example 
- Create Test Table 
IF  object_id (N ' Test ' , N ' the U- ' ) IS  Not  null 
  drop  Table Test
 Go 
with a PivotTable AS 
( 
  SELECT  ' XXX '  AS CZY, ' thumbs up '  AS czlx, 2  as num
   union  all 
  select  ' xxx ' , ' Browse '  as czlx, 14 as num
   union  all 
  select  ' yyy ' , ' Browse '  as czlx, 10  as num
   union  all 
  select  ' zzz ' , ' Browse ' , 30 
  union  all 
  select  ' zzz ' , ' Like ' , 3  
) 
select  *  into test from PivotTable
 Go 
- create a stored procedure 
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 ;

 

Guess you like

Origin www.cnblogs.com/adsoft/p/12701454.html