-------------------------------------------
| CustomerID | Action | Amount |
|-------------------------------------------|
| 111 | deposit | 100 |
| 111 | withdrawl | 25 |
| 222 | deposit | 500 |
| 222 | deposit | 100 |
| 333 | withdrawl | 100 |
| 333 | deposit | 100 |
-------------------------------------------
写一个查询,每个customerID
将显示该客户的总Amount
,其中存款操作被添加到总数中,而提款从总数中减去
答案 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
(如果withdrawl
或other
“只有一个替代”)使用DECODE
伪代码编写简单查询:
select CustomerID "Customer ID", sum(decode(Action,'withdrawl',-Amount,Amount)) "Total Amount"
from inventory
group by CustomerID
order by CustomerID;