我們知道如何做簡單的 MySQL 算術——例如:
mysql> select 10-7 as 'result';
--------
| result |
--------
| 3 |
--------
但是如果“10”和“7”本身就是 MySQL 選擇查詢的結果,我們如何計算?- 例如:
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 |
---------
uj5u.com熱心網友回復:
UNION 將結果行附加到查詢結果中。
您可以使用JOIN附加列,但是使用稍微不同的查詢會給出您的結果。
select sum(if(type='dr', amount, -amount)) as 'balance'
from table
where date between "2019-06-01" and "2019-06-30"
這里我們使用IF函式來確定我們是在增加還是減少金額。
uj5u.com熱心網友回復:
您可以嘗試使用條件聚合函式,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://www.uj5u.com/ruanti/402044.html
上一篇:如何通過我們知道Point1和Point2的位置和線Point1到Point2的長度以及線Point1到Point3的長度來找到Point3位置?
下一篇:無法找到數字1-20的最小公倍數
