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

MYSQL
MySQL菜鸟入门指南
mysql常识和基本操作
MySQL数据库函数详解(1)
MySQL数据库函数详解(2)
MySQL数据库函数详解(3)
MySQL数据库函数详解(4)
MySQL数据库函数详解(5)
mysql使用指南(上)
MYSQL使用指南(下)
MySQL实现表中取出随机数据
从MySQL导出XLS数据库工具(跨平台)
禁止Mysql默认端口访问Internet
MYSQL数据同步备份复制
MySQL数据库和备份与恢复
使用MySql ODBC进行MYsql和MSsql的数据转换
MySQL数据库格式轻松转
使用MySQL内建复制功能来最佳化可用性
MySQL中如何实现Top N及M至N段的记录查询?
MySQL丢了root密码怎么办?
MySQL 4.1 的安装和升级

MYSQL 中的 SQL实现动态交叉表


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 66 ::
收藏到网摘: 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