Oracle 11g - 将总列添加到数据透视表

时间:2015-04-15 01:03:04

标签: oracle oracle11g pivot-table

我使用来自多个表的数据(使用JOINS)创建了一个数据透视表。如何在表格中添加另一列,从每行添加每列?

示例:

Category  |  A  |  B  |  C |
ABC          1     1     1
A            1     0     0
B            0     1     0
C            0     0     1


Category  |  A  |  B  |  C | TOTAL
ABC          1     1     1    3
A            1     0     0    1
B            0     1     0    1 
C            0     0     1    1

1 个答案:

答案 0 :(得分:0)

SCOTT@research 15-APR-15> select * from testing ;

CATEG          A          B          C
----- ---------- ---------- ----------
ABC            1          1          1
A              1          0          0
B              0          1          0
C              0          0          1

SCOTT@research 15-APR-15> select category,a,b,c, sum(a+b+c) as "total" from testing group by category,a,b,c order by category;

CATEG          A          B          C      total
----- ---------- ---------- ---------- ----------
A              1          0          0          1
ABC            1          1          1          3
B              0          1          0          1
C              0          0          1          1

如果你想添加一个列,那么可以添加一个使用过程来使用它更新值,

alter table testing add total int;

使用此程序更新值

create or replace procedure add_Test
is
sqlis varchar2(10);
total1 int;
begin
for i in (select * from testing) loop
  select sum(a+b+c) into total1 from testing where category=i.category;
 update testing set total=total1 where category=i.category;
 end loop;
 commit;
 end;


exec add_test;

SCOTT@research 15-APR-15> select * from testing;

CATEG          A          B          C      TOTAL
----- ---------- ---------- ---------- ----------
ABC            1          1          1          3
A              1          0          0          1
B              0          1          0          1
C              0          0          1          1