添加和撤销存款的SQL总金额

时间:2017-12-27 22:52:22

标签: sql oracle

 -------------------------------------------  
|  CustomerID |    Action      |    Amount  |
|-------------------------------------------|
|   111       |     deposit    |      100   |
|   111       |    withdrawl   |       25   | 
|   222       |     deposit    |      500   |
|   222       |     deposit    |      100   |
|   333       |    withdrawl   |      100   |
|   333       |     deposit    |      100   |
 -------------------------------------------  

写一个查询,每个customerID将显示该客户的总Amount,其中存款操作被添加到总数中,而提款从总数中减去

2 个答案:

答案 0 :(得分:2)

使用CASE WHEN,您可以根据其他字段(AMOUNT)的值在计算中区别对待ACTION列。

SELECT CUSTOMERID,
SUM(CASE WHEN ACTION = 'DEPOSIT' THEN AMOUNT
         WHEN ACTION = 'WITHDRAWL' THEN -AMOUNT ELSE 0 END) AS TOTAL_AMOUNT
FROM
TABLE1
GROUP BY CUSTOMERID;

答案 1 :(得分:0)

您可以直接使用IF - ELSE logic(如果withdrawlother“只有一个替代”)使用DECODE伪代码编写简单查询:

select CustomerID "Customer ID", sum(decode(Action,'withdrawl',-Amount,Amount)) "Total Amount"
  from inventory
 group by CustomerID 
 order by CustomerID;

D e m o