在开发项目过程中经常要用到交叉表,方便用户查看数据,交叉表--就是行转换成列。动态的交叉表就比较少用了。下面的SQL提供了一种思路,希望对需要的人有所帮助。
if object_id('Col_Row') is not null
drop procedure Col_Row
go
create procedure Col_Row
(@table_to_turn varchar(255), --待旋转的表
@key_col varchar(255), --保留的关键字段
@col_know_how varchar(255), --生成列名的字段
@col_to_turn varchar(255), --作为值的字段
@how_to varchar(20)='sum') --生成值的方式 sum min max avg ,etc.
/*
过程作用,根据纵向数据生成新横向结构
Created by Rami
created date 2008-08-29
*/
as
declare @exec varchar(8000)
create table #tmp (col varchar(255))
set @exec='select distinct '+@col_know_how+ ' from '+@table_to_turn
insert into #tmp exec (@exec)
set @exec=''
select @exec=@exec+@how_to+'(case when ['+@col_know_how+']= '''+col+''' then ['+@col_to_turn +'] else null end ) as ['+col+'],'
from #tmp
set @exec=left(@exec,len(@exec)-1)
set @exec='select ['+@key_col+'],'+@exec+' from ['+@table_to_turn+'] group by ['+@key_col+']'
exec(@exec)
go
--exec Col_Row 'empreceive','EmpCode','RpName','RPQty','sum'