create table A
(
年月 varchar(20),
数量 int,
金额 int
)
insert A
select '2005-5',100,1000 union
select '2005-6',2000,20000 union
select '2005-7',300,30000--查询
declare @sql varchar(8000),@sql2 varchar(8000),@sql3 varchar(8000)
select @sql='',@sql2='',@sql3=''
select @sql=@sql+','+quotename(年月)+' int'
,@sql2=@sql2+','+convert(varchar,数量)
,@sql3=@sql3+','+convert(varchar,金额)
from A
select @sql='create table #('+stuff(@sql,1,1,'')+')'
+' insert # select '+stuff(@sql2,1,1,'')
+' insert # select '+stuff(@sql3,1,1,'')
+' select * from #'
print @sql
exec(@sql)--删除测试环境
drop table A --结果
/*
2005-5 2005-6 2005-7
----------- ----------- -----------
100 2000 300
1000 20000 30000
*/
(
年月 varchar(20),
数量 int,
金额 int
)
insert A
select '2005-5',100,1000 union
select '2005-6',2000,20000 union
select '2005-7',300,30000--查询
declare @sql varchar(8000),@sql2 varchar(8000),@sql3 varchar(8000)
select @sql='',@sql2='',@sql3=''
select @sql=@sql+','+quotename(年月)+' int'
,@sql2=@sql2+','+convert(varchar,数量)
,@sql3=@sql3+','+convert(varchar,金额)
from A
select @sql='create table #('+stuff(@sql,1,1,'')+')'
+' insert # select '+stuff(@sql2,1,1,'')
+' insert # select '+stuff(@sql3,1,1,'')
+' select * from #'
print @sql
exec(@sql)--删除测试环境
drop table A --结果
/*
2005-5 2005-6 2005-7
----------- ----------- -----------
100 2000 300
1000 20000 30000
*/
Create Table t (年月 varchar(20),数量 int,金额 int)
insert into t select '2005-5',100,1000
union all select '2005-6',2000,20000
union all select '2005-7',300,30000
--动态SQL
declare @s varchar(200),@s1 varchar(200)
select @s='',@s1=''
select @s=@s+' ['+年月+']=sum(case when 年月='''+年月+''' Then 数量 end),'
from T
group by 年月
set @s='select 年月=''数量'','+stuff(@s,len(@s),1,'')+'from T'
select @s1=@s1+' ['+年月+']=sum(case when 年月='''+年月+''' Then 金额 end),'
from T
group by 年月
set @s1='select 年月=''金额'','+stuff(@s1,len(@s1),1,'')+'from T'
exec(@s+' UNION all '+@s1)--执行结果
年月 2005-5 2005-6 2005-7
---- ----------- ----------- -----------
数量 100 2000 300
金额 1000 20000 30000--删除测试环境
Drop Table T
insert into tb select '2005-5',100,1000
union all select '2005-6',2000,20000
union all select '2005-7',300,30000
godeclare @sql1 varchar(8000),@sql2 varchar(8000),@sql3 varchar(8000)
select @sql1='select [年月]=''数量''',@sql2='select [年月]=''金额'''
select @sql1=@sql1+',['+年月+']=sum(case 年月 when '''+年月+''' then 数量 end)' from tb group by 年月
select @sql2=@sql2+',['+年月+']=sum(case 年月 when '''+年月+''' then 金额 end)' from tb group by 年月
set @sql3=@sql1+' from tb union all '+@sql2+' from tb 'exec(@sql3)
go
drop table tb
/*
年月 2005-5 2005-6 2005-7
---- ----------- ----------- -----------
数量 100 2000 300
金额 1000 20000 30000警告: 聚合或其它 SET 操作消除了空值。
*/