0

I have a table 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

I want columns Cap_Up and Cap_Down be updated for Id=1000 based on values of these column for Id=1001 and Id=1002, for all periods, as follows:

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

So, the output will be, 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

2 Answers 2

3

Below is one possible solution:

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
;

Check at SQLFiddle: http://sqlfiddle.com/#!4/e9c61/1

Sign up to request clarification or add additional context in comments.

Comments

0

try this query it can help you so much because you can control this query with where clause:

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.