我如何使用两个sum()与两个不同的条件?

时间:2018-03-21 16:25:52

标签: sql sql-server sum

我有Table1,在此表中用户可以向他们的帐户收费

 userid       action       amount
   1          Deposit      10000
   1          removal      500
   2          Deposit      20000
   2          removal      13000

现在我想为每个用户选择剩余费用。
总和(金额)with conditions WHERE action='Deposit' - SUM(金额)with conditions WHERE action='removal'

现在结果代码应该如下:

 userid       reamine charge
   1              9500
   2              7000

非常感谢

4 个答案:

答案 0 :(得分:0)

虽然我同意你应该存储否定词的评论,但这是一个解决方案。

DECLARE @data TABLE ([userid] int,[action] NVARCHAR(200),Amount MONEY)

INSERT INTO @data ([userid],[action],Amount) SELECT 1,'Deposit',10000
INSERT INTO @data ([userid],[action],Amount) SELECT 1,'removal',500
INSERT INTO @data ([userid],[action],Amount) SELECT 2,'Deposit',20000
INSERT INTO @data ([userid],[action],Amount) SELECT 2,'removal',13000

select
    [userid],
    sum (
        CASE
            WHEN [action]='Deposit' THEN Amount
            ELSE -1.0 * Amount
        END
    ) AS [reamine charge]
FROM @DATA
group by [userid]

您要求的解决方案不是最好的,但现在是:

select
    [userid],
    (
       sum(CASE WHEN [action]='Deposit' THEN Amount ELSE 0 END)
       -sum(CASE WHEN [action]='removal' THEN Amount ELSE 0 END)
    ) AS [reamine charge]
FROM @DATA
group by [userid]

答案 1 :(得分:-1)

您应该仅对特定过滤器求和。

SELECT
    userId,
    SUM(CASE WHEN action = 'deposit' THEN amount END) TotalDeposits,
    SUM(CASE WHEN action = 'removal' THEN amount END) TotalRemovals,
    SUM(CASE WHEN action = 'deposit' THEN amount END)
        - SUM(CASE WHEN action = 'removal' THEN amount END) TotalAvailable
FROM
    Table1
GROUP BY
    userId

答案 2 :(得分:-1)

select client_id, credits,debits, credits-debits as balance
from (SELECT 
client_id,
SUM(case when ACTION_TYPE='Deposit' then action_amount else 0 end) AS credits, 
SUM(case when ACTION_TYPE='removal' then action_amount else 0 end) AS debits
FROM categories 
GROUP BY client_id) a
where debits-credits<>0;

使用SUM()可以满足您的需求.. Fiddle

答案 3 :(得分:-1)

Here is another way to achive what u want, i will leave 

我的陈述中有更多信息,所以你可以看到实际发生的事情

SELECT ts.*, removal.*, 
SUM(ts.amount) as total_deposit, 
SUM(removal.amount) AS total_removal,  
SUM(ts.amount) - SUM(removal.amount) as result FROM Table1 as ts
INNER JOIN Table1 as removal ON ts.userId=removal.userId
WHERE ts.action = 'Deposit' AND removal.action='removal'
GROUP BY ts.userId, ts.action


and this is cleared variant of the statement

SELECT ts.userId,
SUM(ts.amount) - SUM(removal.amount) as result 
FROM Table1 as ts
INNER JOIN Table1 as removal ON ts.userId=removal.userId
WHERE ts.action = 'Deposit' AND removal.action='removal'
GROUP BY ts.userId, ts.action