Table A1 Table B1
A --100 id =1 A --100 id=1
B -- 100 id =2 A -100 id=1
C -- 200 id=3 A - 100 id =1
需要对两个表中的所有值求和,其中id = 1。
select (SUM(A1.A) + SUM(nvl(B1.A,0))) SUM from A1 a, B1 b where a.id='1' AND b.id='1';
我得到的金额为600,但应该是400
答案 0 :(得分:0)
这样的事情应该有效。
SELECT id, SUM(A) as Totals FROM
(
SELECT id, A FROM A1
UNION ALL
SELECT id, A FROM B1
) AS tblData
GROUP BY id
答案 1 :(得分:0)
您使用了CROSS JOIN
(笛卡尔积),因此您获得了600 ..
您可以尝试使用UNION
结合两个表格。
SELECT SUM(T.Totle)
FROM
(
select SUM(A1.A) Totle from A1 a where a.id='1'
UNION ALL
select SUM(B1.A) Totle from B1 b where b.id='1'
) T
答案 2 :(得分:0)
您可以使用:
SELECT COALESCE((SELECT SUM(A) FROM A1 WHERE ID = 1), 0) +
COALESCE((SELECT SUM(A) FROM B1 WHERE ID = 1), 0)
答案 3 :(得分:0)
你可以这样做
select sum(A) as total
from
(
select A
from A1 where id = 1
union all
select A
from B1 where id = 1
) t
答案 4 :(得分:0)
这是一个不使用子查询的方法(虽然我不推荐它):
select coalesce(sum(a.a), 0) + coalesce(sum(b.b), 0)
from a full outer join
b
on 1 = 0
where a.id = 1 or b.id = 1;