--我猜的--有表及数据 create table 表(项目 varchar(10),日期 datetime,值 int) insert 表 select '数量','2004-02-02',1 union all select '数量','2004-02-03',1 union all select '数量','2004-02-04',1 union all select '金额','2004-02-02',20 union all select '金额','2004-02-03',20 union all select '金额','2004-02-04',15 go/*--要求得到结果 20040202 20040203 20040204 金额 20 20 15 数量 1 1 1 --*/--查询处理 declare @s varchar(8000) set @s='' select @s=@s+',['+convert(char(8),日期,112)+']=sum(case dt when ''' +convert(char(8),日期,112)+''' then 值 else 0 end)' from 表 group by 日期 exec('select 项目'+@s+' from( select 项目,dt=convert(char(8),日期,112),值 from 表 )a group by 项目') go--删除测试 drop table 表/*--测试结果 项目 20040202 20040203 20040204 ---------- ----------- ----------- ----------- 金额 20 20 15 数量 1 1 1 --*/
create table 表(项目 varchar(10),日期 datetime,值 int)
insert 表 select '数量','2004-02-02',1
union all select '数量','2004-02-03',1
union all select '数量','2004-02-04',1
union all select '金额','2004-02-02',20
union all select '金额','2004-02-03',20
union all select '金额','2004-02-04',15
go/*--要求得到结果 20040202 20040203 20040204
金额 20 20 15
数量 1 1 1
--*/--查询处理
declare @s varchar(8000)
set @s=''
select @s=@s+',['+convert(char(8),日期,112)+']=sum(case dt when '''
+convert(char(8),日期,112)+''' then 值 else 0 end)'
from 表
group by 日期
exec('select 项目'+@s+'
from(
select 项目,dt=convert(char(8),日期,112),值 from 表
)a group by 项目')
go--删除测试
drop table 表/*--测试结果
项目 20040202 20040203 20040204
---------- ----------- ----------- -----------
金额 20 20 15
数量 1 1 1
--*/