我有一张表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=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
答案 0 :(得分: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
答案 1 :(得分: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);