日期:2014-05-17  浏览次数:20699 次

多张表分组,left join 但是decode只能判断一个字段,我现在需要判断2个的基础上sum,怎么办

create table t1 (y_no number,score varchar2(10),d_no number);

insert into t1 values (1,'合格',33);
insert into t1 values (1,'不合格',55);
insert into t1 values (2,'合格',22);
insert into t1 values (2,'不合格',44);
insert into t1 values (2,'合格',33);
insert into t1 values (3,'不合格',22);
insert into t1 values (4,'合格',11);


select t1.y_no 员工,
  nvl(sum(decode(score,'合格',1,0)),0) 合格数,
  nvl(sum(decode(score,'不合格',1,0)),0) 不合格数,
  decode(sum(case when score='合格' and d_no=11 then 1 when score='不合格' and d_no=11 then 0 end),1,'合格',0,'不合格') 打分人11,
  decode(sum(case when score='合格' and d_no=22 then 1 when score='不合格' and d_no=22 then 0 end),1,'合格',0,'不合格') 打分人22,
  decode(sum(case when score='合格' and d_no=33 then 1 when score='不合格' and d_no=33 then 0 end),1,'合格',0,'不合格') 打分人33,
  decode(sum(case when score='合格' and d_no=44 then 1 when score='不合格' and d_no=44 then 0 end),1,'合格',0,'不合格') 打分人44,
  decode(sum(case when score='合格' and d_no=55 then 1 when score='不合格' and d_no=55 then 0 end),1,'合格',0,'不合格') 打分人55
from t1
group by t1.y_no
order by t1.y_no

员工 合格数 不合格数 打分人11 打分人22 打分人33 打分人44 打分人55
--------------------------------------
1 1 1 合格 不合格
2 2 1 合格 合格 不合格  
3 0 1 不合格  
4 1 0 合格  


------解决方案--------------------
如果要判断的话 可以结合sign函数

SQL code

select decode(sign(2-1),1,'大于',0,'等于',-1,'小于') from dual
union all
select decode(sign(1-2),1,'大于',0,'等于',-1,'小于') from dual
union all
select decode(sign(1-1),1,'大于',0,'等于',-1,'小于') from dual

     ds
-------------------------
1    大于
2    小于
3    等于