--没有sql server用oracle简单写了一个 -- create table t(qty int,date1 varchar2(10),date2 varchar2(10)) insert into t select 100,'00','1' from dual union all select 100,'01','1' from dual union all select 100,'02','1' from dual union all select 100,'00','2' from dual union all select 100,'01','2' from dual union all select 100,'02','2' from dual; --执行查询(如果不想动态的查询你根据年份生成下面的sum部分就可以了) select date2, sum(case when date1='00' then qty else 0 end) "00年", sum(case when date1='01' then qty else 0 end) "01年", sum(case when date1='02' then qty else 0 end) "02年" from t group by date2 --输出结果 DATE2 00年 01年 02年 ---------- ---------- ---------- ---------- 1 100 100 100 2 100 100 100
LZ阿, hongqi162(失踪的月亮) 并不是给你求和阿,那是在做标准的行列转换哦!!!
需要使用存储过程来解决,没有sqlserver下面的代码没有测试,原理应该是这样的declare @s varchar(8000); begin select @s=@s+',sum(case when date1='+date1+' then qty else 0 end as '+date1+'' from t group by date1; exec('select date2 '+@s+' from t'); end;
http://www.e-jun.com/down.asp?file=EjunExcelRW.rar
--
create table t(qty int,date1 varchar2(10),date2 varchar2(10))
insert into t
select 100,'00','1' from dual union all
select 100,'01','1' from dual union all
select 100,'02','1' from dual union all
select 100,'00','2' from dual union all
select 100,'01','2' from dual union all
select 100,'02','2' from dual;
--执行查询(如果不想动态的查询你根据年份生成下面的sum部分就可以了)
select
date2,
sum(case when date1='00' then qty else 0 end) "00年",
sum(case when date1='01' then qty else 0 end) "01年",
sum(case when date1='02' then qty else 0 end) "02年"
from t group by date2
--输出结果
DATE2 00年 01年 02年
---------- ---------- ---------- ----------
1 100 100 100
2 100 100 100
@s varchar(8000);
begin
select @s=@s+',sum(case when date1='+date1+' then qty else 0 end as '+date1+'' from t group by date1;
exec('select date2 '+@s+' from t');
end;