当前位置: 代码迷 >> Sql Server >> 继续发帖。该如何处理
  详细解决方案

继续发帖。该如何处理

热度:103   发布时间:2016-04-27 14:48:06.0
继续发帖。。。。
把动态行转列里的结果放到视图或者表里(只要是其他表能引用的就可以了)
测试数据:
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 hlselect 'swz','2011-04-4',12 union allselect 'swz','2011-04-4',23 union allselect 'swz','2011-06-4',12 union allselect 'swz','2011-04-4',12 union allselect 'cl','2011-04-4',134 union allselect 'cl','2011-03-4',134 union allselect '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 aset @sql = @sql + ' into newh1 from hl group by name'exec(@sql) select * from newh1/*姓名                     3           4           6           9      ---------------------- ----------- ----------- ----------- -----------cl                     134         134         0           134swz                    0           23          12          0*/
------解决方案--------------------
创建一个临时表

然后insert into #tb exec(@sql)
  相关解决方案