简体   繁体   English

如何基于另一列在同一行中减去mysql

[英]how to subtract in mysql at the same row based on another column

I am trying to subtract sold dollars against bought dollars. 我试图减去卖出的美元兑买入的美元。

**|Tran_ID|Currency_type|currency_Amount|Local_Amount|  Rate  |Tran_type| ** 
  | 85     |   USD      |   2500       |    1581.54  |1.58074 |  Bought |
  | 78     |   USD      |   3487.57    |    2206.29  |1.58074 |  Bought |
  | 86     |   USD      |   100        |    63.26    |1.58074 |  Bought |
  | 87     |   USD      |   94.17      |    63.26    |1.48866 |  Sold   |
  | 88     |   USD      |   2600       |    1746.54  |1.48866 |  Sold   |
  | 89     |   USD      |   2600       |    1746.54  |1.48866 |  Sold   |

I can Add the total values of dollars sold or bought with the query below 我可以使用下面的查询添加已售出或已购买的美元总价值

SELECT Currency_type, sum( currency_Amount ) AS total_bought
FROM Transaction
WHERE Currency_type=  'USD'
AND Tran_type =  'Bought'       <==  **or 'Sold'**

the outcome is below 结果如下

**|Currency_type | total_bought    |**
|USD             |6087.570068359375|

您只需在交易类型上设置标志:

SUM(currency_Amount * IF(Tran_type = "Bought", 1, -1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM