有2个表a, b如下: 用Update 语句把b.value的值加到a.value上, 用key对应,
create table a
(
key varchar(10),
value number
);create table b
(
key varchar(10),
value number
);
--a, b中的数据
insert into a
select '001', 11 from dual union
select '002', 22 from dual union
select '003', 33 from dual;insert into b
select '001', 11 from dual union
select '001', 13 from dual union
select '002', 10 from dual union
select '002', 22 from dual ;
commit;--写了以下update语句来更新.
update a set value = value +
(
Select nvl(sum(b.Value), 0) from b where b.key = a.key
group by b.key
);commit;可是 select * from a 得到的结果却是:
/*
Key Value
001 35
002 54
003
*/003中的值没有了,请问正确的update语句应该怎么写?多谢了!
看看这个贴,和你一样的场景,
http://topic.csdn.net/u/20090703/13/1119c552-cc1b-4140-a7c1-ae05703bb5f8.html是不是你问过的 看我最后的回答
update a set value =
(
Select sum(a.Value + b.Value) from b where b.key = a.key
group by b.key
);得到的结果是一样的。
看到区别了,你这个是需要做sum的,我改一下,测好就给你。
先试试这个复杂一些的,等下在裁剪一下update a set value = value + (
select sum from (select a.key, nvl(b.sum,0) sum from (Select key, nvl(sum(b.Value), 0) sum from b group by key) b, a where a.key=b.key(+)) where a.key=key)
(select c.value from (Select a.key, sum(nvl(b.Value,0)) value from a,b
where b.key(+) = a.key
group by a.key) c where a.key=c.key)
最简单的update a set value = value +
nvl((
Select nvl(sum(b.Value), 0) from b where b.key = a.key
group by b.key
),0);
更正以下:刚才测试错误,inthirties 大哥是正确的。
本来想做个直接更新view的,但是太麻烦了,必须要有一个unique的检查。后来看回我自己的第一个回复,为什么003会为null就是因为 value = value + null, 既然如此,那么简化一下思路,不就是 value = value + nvl(null, 0) 就可以了么。所以就按自己的想法尝试了一下,一起推断都OK。所以,结果和最先的推断完全一致了。
(
Select nvl(sum(b.Value), 0) from b where b.key = a.key
group by b.key
),0);这个不就行了么?