Oracle中的SQL查询语句:根据同一张表中的某一字段的不同条件分别求另一字段的和。

2024-12-03 09:30:01
推荐回答(2个)
回答(1):

select 部门,sum(decode(正负,'Y',分值,0)) 正分,sum(decode(正负,'N',分值,0)) 负分
group by 部门

回答(2):

create table #a (id int,bm char(10),fz int,zf char(10))
insert #a select 1,'a',1,'y'
insert #a select 2,'b',2,'n'
insert #a select 3,'c',5,'y'
insert #a select 4,'a',4,'n'
insert #a select 5,'a',3,'y'
insert #a select 6,'b',6,'n'
insert #a select 7,'c',3,'y'

declare @sql varchar(800)
set @sql='select bm'
select @sql =@sql+', sum(case zf when '''+zf+''' then fz else 0 end )['+zf+']'
from (select distinct zf from #A ) as a
set @sql=@sql+'from #a group by bm'
exec(@sql)