SQL实现动态交叉表:
以下为引用的内容:
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
ALTER procedure CrossTable
@strTableName as varchar(50)='', --查询表
@strCol as varchar(50)='',
@strGroup as varchar(50)='',--分组字段
@strNumber as varchar(50)='',--被统计的字段
@strCompute as varchar(50)='Sum'--运算方式
declare @strSql as varchar(1000),@strTempCol as varchar(100)
execute ('DECLARE corss_cursor CURSOR FOR SELECT DISTINCT '+@strCol+' from '+@strTableName+' for read only') --生成游标
begin
set nocount on
set @strSql='select '+@strGroup+','+@strCompute+'('+@strNumber+') as ['+@strNumber+']'
open corss_cursor
while(0=0)
begin
fetch next from corss_cursor
into @strTempCol
if(@@fetch_status <>0) break
set @strSql=@strSql+','+@strCompute+'( case '+@strCol+' when '''+@strTempCol+''' then '+@strNumber +' else 0 end ) as ['+@strTempCol+']'
set @strsql=@strSql+' from '+@strTableName+' group by '+@strGroup
print @strSql
execute(@strSql)
if @@error <>0 return @@error
print @@error
close corss_cursor
deallocate corss_cursor return 0
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON
通过上文中的方法就能够轻松的实现动态交叉表,文章主要是以代码的形式展现的,可能是不太容易理解,可只要大家认真学习,相信就没什么能够难到大家,希望大家都能够从中收获。
【编辑推荐】