日期:2014-05-18  浏览次数:20470 次

继续发帖。。。。
把动态行转列里的结果放到视图或者表里(只要是其他表能引用的就可以了)
测试数据:
create table hl(name char(22),dated datetime,shuliang int)

insert into hl
select 'swz','2011-04-4',12 union all
select 'swz','2011-04-4',23 union all
select 'swz','2011-06-4',12 union all
select 'swz','2011-04-4',12 union all
select 'cl','2011-04-4',134 union all
select 'cl','2011-03-4',134 union all
select 'cl','2011-09-4',134 
--动态行转列(要转的结果)
declare @sql varchar(8000)
set @sql = 'select Name as ' + '姓名'
select @sql = @sql + ' , max(case cast(datepart(mm,dated) as char(5)) when ''' + cast(datepart(mm,dated) as char(5)) + ''' then shuliang else 0 end) [' + cast(datepart(mm,dated) as char(7)) + ']'
from (select distinct dated from hl) as a
set @sql = @sql + ' from hl group by name'
exec(@sql) 



------解决方案--------------------
SQL code

create table hl(name char(22),dated datetime,shuliang int)

insert into hl
select 'swz','2011-04-4',12 union all
select 'swz','2011-04-4',23 union all
select 'swz','2011-06-4',12 union all
select 'swz','2011-04-4',12 union all
select 'cl','2011-04-4',134 union all
select 'cl','2011-03-4',134 union all
select 'cl','2011-09-4',134  
--动态行转列(要转的结果)
declare @sql varchar(8000)
set @sql = 'select Name as ' + '姓名'
select @sql = @sql + ' , max(case cast(datepart(mm,dated) as char(5)) when ''' + cast(datepart(mm,dated) as char(5)) + ''' then shuliang else 0 end) [' + cast(datepart(mm,dated) as char(7)) + ']'
from (select distinct dated from hl) as a
set @sql = @sql + ' into newh1 from hl group by name'
exec(@sql) 

select * from newh1

/*
姓名                     3           4           6           9      
---------------------- ----------- ----------- ----------- -----------
cl                     134         134         0           134
swz                    0           23          12          0
*/

------解决方案--------------------
创建一个临时表

然后insert into #tb exec(@sql)