关于oracle采用pivot函数列转行后一些列的值为null处理

假设现在有三张表,一张类别表,一张员工表,一张交易明细表
create table kinds( name varchar2(32) ,code char(2));
insert into kinds(name, code) values('name1','01');
insert into kinds(name, code) values('name1','02');
insert into kinds(name, code) values('name1','03');
insert into kinds(name, code) values('name1','04');
create table trade_dtl(empid number(5),empname varchar2(9),kind_code char(2),amount number(10,2),trade_date varchar2(8));
insert into trade_dtl(empid, empname, kind_code, amount, trade_date) values(1,'张三','01',100,'20151202');
insert into trade_dtl(empid, empname, kind_code, amount, trade_date) values(1,'张三','02',100,'20151102');
insert into trade_dtl(empid, empname, kind_code, amount, trade_date) values(2,'李四','03',100,'20151102');
insert into trade_dtl(empid, empname, kind_code, amount, trade_date) values(2,'李四','04',100,'20151202');

现在要看每个人每种商品汇总信息,可以写如下语句

select * 
  from(select d.empid,d.empname,d.kind_code,d.amount 
         from trade_dtl d) 
  pivot(sum(amount) as amount,count(1) as num for kind_code in ('01' name1,'02' name2,'03' name3,'04' name4)) 

但是,不管是李四还是张三都没有所有类别的交易明细,至少缺了一种,比如:张三从trade_dtl表中取的数据就不含‘03’这种类别的交易明细

而且类别这张表是可变的,所以要让null显示为0,则要改为:

select *
  from (select t1.code, t1.empid, t1.empname, nvl(t2.amount, 0) as amount
          from (select d.code, d.name, e.empid, e.empname
                  from employee e, kinds d) t1
          left join trade_dtl t2
            on t1.empid = t2.empid
           and t1.code = t2.kind_code) 
   pivot(sum(amount) as amount, count(1) as num for code in('01' name1, '02' name2, '03' name3, '04' name4))
这个改动的思路就是把kinds表作为主表,但这个写法我个人觉得不是太好,欢迎批评指正

你可能感兴趣的:(oracle)