34,587
社区成员
发帖
与我相关
我的任务
分享
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 t1 from hl group by name' --在查询里使用into到一个新表中
exec(@sql)
select * from t1 --查询新表
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
*/