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_UpCap_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

以下は、考えられる解決策の 1 つです。

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 に答える