如何使用条件的SQL SUM

时间:2015-07-27 21:01:08

标签: sql sum

我有一个交易表,想要根据交易类型进行计算。怎么样?

表:

id | amount | type
--------------------
01 | 230    | IncomingTransfer
02 | 100    | OutcomingTransfer
03 | 20     | IncomingTransfer

逻辑:

SELECT SUM(amount)
IF IncomingTransfer
    + 230
    + 20
ELSE IF OutcomingTransfer
    - 100

Total amount: +150

3 个答案:

答案 0 :(得分:6)

就像我的 sqlfiddle 一样简单:

&

答案 1 :(得分:1)

SELECT SUM(amount) FROM (
   SELECT CASE WHEN type='IncomingTransfer'
      THEN +amount
      ELSE -amount
      END as amount
   FROM MyTable
) as data

答案 2 :(得分:0)

我会用:

    SELECT Amount = SUM(CASE WHEN Type = 'OutcomingTransfer' then (Amount*-1) 
                    ELSE Amount END)
    FROM <Table>
    GROUP BY <Grouping Field>