SQL實現(xiàn)動態(tài)交叉表
SQL實現(xiàn)動態(tài)交叉表:
以下為引用的內(nèi)容:
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)='',--被統(tǒng)計的字段
  @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') --生成游標(biāo)
  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
通過上文中的方法就能夠輕松的實現(xiàn)動態(tài)交叉表,文章主要是以代碼的形式展現(xiàn)的,可能是不太容易理解,可只要大家認(rèn)真學(xué)習(xí),相信就沒什么能夠難到大家,希望大家都能夠從中收獲。
【編輯推薦】















 
 
 


 
 
 
 