SQL:基于列值做加/减

时间:2019-08-22 16:10:58

标签: sql sql-server

我在sqltable中有如下数据:

+----+-------+-------------+--------+
| Id | PayId | DeductionId | Amount |
+----+-------+-------------+--------+
|  1 |     1 |           0 |    100 |
|  2 |     2 |           0 |    250 |
|  1 |     0 |           3 |     50 |
|  2 |     0 |           4 |     75 |
+----+-------+-------------+--------+

因此,在输出中,需要对Id进行分组,并且当PayId不为零时,进行金额之和;而当DedctionId为非零时,则进行金额之和,然后减去这两个值。因此需要如下所示的输出:

+----+--------+
| Id | Amount |
+----+--------+
|  1 |    50  |
|  2 |    175 |
+----+--------+

该怎么做?

3 个答案:

答案 0 :(得分:2)

希望两者都不是非零的。您只需要条件聚合:

select id,
       sum(case when payid > 0 then amount
                when deductionid > 0 then - amount
                else 0
           end) as amount
from t
group by id;

答案 1 :(得分:1)

对CUM使用CASE语句:

select 
  Id,
  sum(
    case when payid <> 0 then amount else 0 end - 
    case when deductionid <> 0 then amount else 0 end
  ) Amount
from tablename
group by id

请参见demo
结果:

> Id | Amount
> -: | -----:
>  1 |     50
>  2 |    175

答案 2 :(得分:0)

一个简单的case表达式应该适合您。

select Id
    , Amount = sum(case when PayID > 0 then Amount else Amount * -1 end)
from YourTable
group by Id