当前位置: 首页 > 图文教程 > 数据库 > MYSQL > SQL实现动态交叉表

MYSQL
怎样可以在Windows上安装多个Mysql
详细讲解MySQL数据库中的安全配置步骤
解析mysql 8小时空闲后连接超时的问题
一起从基础入手来打开MySQL数据库之门
MySQL数据库中的Show命令具体用法
怎样在MySQL的数据库中定义外键详解
MySQL数据库用户帐号管理基础知识详解
MySQL从旧的版本升级为新的版本全攻略
用Tomcat和MySQL生成动态内容详解
讲解查看MySQL数据库错误码的三个方法
数据库经验:如何简单安装MySQL数据库
MySQL数据库双机热备的配置方法详解
在SUSE10下安装和配置MySQL数据库
MySQL数据库本地备份和双机相互备份
MySQL数据库常见的出错代码及出错信息
带你轻松玩转MySQL数据库的异常处理
用实例管理器轻松管理多个MySQL实例
MySQL性能调整之my.cnf文件的配置方法
Replace INTO与INSERT INTO的不同之处
循序渐进讲解MySQL数据库的性能调整

MYSQL 中的 SQL实现动态交叉表


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 57 ::
收藏到网摘: n/a

以下为引用的内容:
SET QUOTED_IDENTIFIER ON
  GO
  SET ANSI_NULLS ON
  GO
  ALTER procedure CrossTable
  @strTableName as varchar(50)='', --查询表
  @strCol as varchar(50)='',
  @strGroup as varchar(50)='',--分组字段
  @strNumber as varchar(50)='',--被统计的字段
  @strCompute as varchar(50)='Sum'--运算方式
  as
  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+']'
  end
  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
  end
  GO
  SET QUOTED_IDENTIFIER OFF
  GO
  SET ANSI_NULLS ON
  GO