0

我有一张桌子t1

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_Up并根据这些列的值Cap_Down更新和,对于所有时期,如下所示:Id=1000Id=1001Id=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
4

2 回答 2

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

于 2013-10-08T13:58:52.653 回答
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);
于 2013-10-09T10:50:22.943 回答