按其他列值更新列值

时间:2014-08-20 05:35:29

标签: sql oracle

如何编写一个查询,它将使用表B中的数据更新表A上的A列? 表A和表B按ID链接。 ID是表A的主键和表B的外键。我需要用id汇总表b中的amount列,然后用ID更新表A中的sum列。

QUERY

create table A
(Id number,
SumAmount number
);

insert into A 
SELECT 1, NULL FROM DUAL
UNION All
SELECT 2, NULL FROM DUAL
UNION ALL
SELECT 3, NULL FROM DUAL
UNION All
SELECT 4, NULL FROM DUAL
UNION ALL
SELECT 5, NULL FROM DUAL
UNION All
SELECT 6, NULL FROM DUAL


create table B
(Id number,
Amount number
);


insert into B
SELECT 1, 100 FROM DUAL
UNION All
SELECT 1, 200 FROM DUAL
UNION ALL
SELECT 1, 320 FROM DUAL
UNION All
SELECT 2, 230 FROM DUAL
UNION ALL
SELECT 4, 246 FROM DUAL
UNION All
SELECT 4, 212 FROM DUAL

我为此写了一个查询,但它不起作用。任何帮助都表示赞赏。

update a
set a.sumamount = (
select sum(b.amount)
from b group by b.id
where a.id = b.id
)

2 个答案:

答案 0 :(得分:1)

如果您交换group bywhere

,您的查询就没问题了
update a
set a.sumamount = (
select sum(b.amount)
from b
where a.id = b.id
group by b.id
);

Example at SQL Fiddle.

答案 1 :(得分:0)

update A set 
SumAmount = (
select sum(B.Amount)
from B group by B.Id
HAVING (A.Id=B.Id) )