我正在计算两个不同表中两个不同列之和的差异。这就是我所拥有的:
SELECT sum(amount)
FROM variable_in
where user_id='111111'
minus
SELECT sum(amount)
FROM variable_out
where user_id='111111'
当我这样做时,我只得到第一个查询结果的输出。如何让它执行两个查询(对于输入和输出表)以及它是否减去金额列的variable_out总数?因为它们都是正整数。
提前致谢!与我的问题相比,我见过的大多数其他提示都过于复杂。
答案 0 :(得分:0)
如何将查询移至from
子句并使用-
:
SELECT in_amount - out_amount
FROM (SELECT sum(amount) as in_amount
FROM variable_in
WHERE user_id = '111111'
) i CROSS JOIN
(SELECT sum(amount) as out_amount
FROM variable_out
WHERE user_id = '111111'
) o;
您的查询混淆了设置操作"减去"使用数值运算符-
。不可否认,他们确实有相同的名字。但minus
适用于集合,而非数字。
我应该指出,您可以将嵌套查询放在FROM
子句中,并使用数字结果("标量子查询"):
SELECT ((SELECT sum(amount) as in_amount
FROM variable_in
WHERE user_id = '111111'
) -
(SELECT sum(amount) as out_amount
FROM variable_out
WHERE user_id = '111111'
) o
) as diff
FROM dual;
答案 1 :(得分:0)
它非常简单......
select
(select sum(amount) from variable_in where user_id='111111')
-
(select sum(amount) from variable_out where user_id='111111')
as amount;