簡體   English   中英

SQL:基於列值做加/減

[英]Sql : Based on column value do sum/substract

我在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 |
+----+--------+

怎么做?

希望兩者都不會非零。 您只需要條件聚合:

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

對SUM使用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

參見演示
結果:

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

一個簡單的case表達式應該適合您。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM