2013-10-08 39 views
0

我有一个表t1值的总和:更新Oracle SQL Developer中列有相同的其他行

Id Period Cap_Up Cap_Down 
============================= 
1000 1  100  200 
1000 2  500  600 
1001 1  200  400 
1001 2  300  150 
1002 1  900  500 
1002 2  250  600 

我想列Cap_UpCap_Down可以为Id=1000基于这些列的值Id=1001和更新Id=1002,所有期限,如下所示:

Cap_Up(1000) = Cap_Up(1001) + Cap_Down(1002) 
Cap_Down(1000) = Cap_Down(1001) + Cap_Up(1002) 

因此,输出将是,t1

Id Period Cap_Up Cap_Down 
============================= 
1000 1  700  1300 
1000 2  900  400 
1001 1  200  400 
1001 2  300  150 
1002 1  900  500 
1002 2  250  600 

回答

3

下面是一个可能的解决方案:

CREATE TABLE test_table (
    id NUMBER, 
    period NUMBER, 
    cap_up NUMBER, 
    cap_down NUMBER 
); 

INSERT INTO test_table VALUES (1000, 1, 100, 200); 
INSERT INTO test_table VALUES (1000, 2, 500, 600); 
INSERT INTO test_table VALUES (1001, 1, 200, 400); 
INSERT INTO test_table VALUES (1001, 2, 300, 150); 
INSERT INTO test_table VALUES (1002, 1, 900, 500); 
INSERT INTO test_table VALUES (1002, 2, 250, 600); 

UPDATE test_table t1 
    SET (cap_up, cap_down) = 
    (SELECT t_1001.cap_up + t_1002.cap_down, 
      t_1001.cap_down + t_1002.cap_up 
     FROM test_table t_1001, test_table t_1002 
    WHERE t_1001.id = 1001 
     AND t_1002.id = 1002 
     AND t_1001.period = t1.period 
     AND t_1002.period = t1.period) 
WHERE t1.id = 1000 
; 

检查在SQLFiddle:http://sqlfiddle.com/#!4/e9c61/1

+0

谢谢。有效。 – Matin

0

尝试此查询它可以帮你这么多,因为你可以控制这个查询用WHERE子句:

create table t2 as 
(select t1.id,t1.period, 
(select t2.cap_up from hatest1 t2 where t2.period = t1.period and t2.id = t1.id+1)+ 
(select t2.cap_down from hatest1 t2 where t2.period = t1.period and t2.id = t1.id+2) as cap_up, 
(select t2.cap_down from hatest1 t2 where t2.period = t1.period and t2.id = t1.id+1)+ 
(select t2.cap_up from hatest1 t2 where t2.period = t1.period and t2.id = t1.id+2) as cap_down 
from t1 where t1.id = 1000); 


insert into hatest2(select * from hatest1 where id>1000); 
相关问题