我们知道如何做简单的MySQL算法,例如:
mysql> select 10-7 as 'result';
+--------+
| result |
+--------+
| 3 |
+--------+
但是,如果"10“和"7”本身就是MySQL select查询的结果,我们如何计算?-例如:
select x.balance from (
select sum(amount) as 'balance'
from table
where date between "2019-06-01" and "2019-06-30"
and type="cr"
) as x
union
select y.balance from (
select sum(amount) as 'balance'
from table
where date between "2019-06-01" and "2019-06-30"
and type="dr"
) as y;
+---------+
| balance |
+---------+
| 5792.00 |
| 6014.26 |
+---------+
我如何将所有这些写成一个查询来获得:
select 5792.00-6014.26 as 'result';
+---------+
| result |
+---------+
| -222.26 |
+---------+
发布于 2022-01-02 08:36:34
UNION
将结果行附加到查询结果。
您可以使用JOIN
来附加列,但是使用查询稍微不同会给出结果。
select sum(if(type='dr', amount, -amount)) as 'balance'
from table
where date between "2019-06-01" and "2019-06-30"
在这里,我们使用IF
函数来确定我们是在加还是减这个量。
发布于 2022-01-02 09:16:39
您可以尝试使用条件聚合函数、SUM
+ CASE WHEN
来做算术。
select sum(CASE WHEN type = 'dr' THEN amount ELSE -amount END) as 'balance'
from table
where
date between "2019-06-01" and "2019-06-30"
and
type IN ('dr','cr')
https://stackoverflow.com/questions/70554406
复制相似问题