SQL查询 - 金额净额

时间:2015-11-09 03:58:15

标签: sql sql-server

我在sql查询中需要帮助,这将根据以下条件给我状态 -

如果Text列具有相同的值,例如(AAA 7 BBB)和Amount列,那个特定的Entt和Text具有相同的+ ve和-ve值,如(266.72),那么status应该是netting

如果Text列具有相同的值,例如(XXX 8 ZZZ)AND Amount列,那个特定的Entt和Text有不同的值+ ve或-ve like(-19.20 / 18.51),那么状态应该是不可能的netting。

对于其余记录,状态应为No Netting

提前致谢!

Text    entt    Amount  Status
XXXX Y3 AT00    29160   Netting
XXXX Y3 AT00    29160   Netting
XXXX Y3 AT00    -29160  Netting
XXXX Y3 AT00    -29160  Netting
XXXX Y3 AT00    27000   Netting
XXXX Y3 AT00    34408.8 No Netting
XXXX Y3 AT00    -27000  Netting
XXXX Z4 AT00    34408.8 No Netting
XXXX Z4 AT00    27000   Netting
XXXX Z4 AT00    -29160  Netting
XXXX Z4 AT00    29160   Netting
XXXX Z4 AT00    -29160  Netting
XXXX Z4 AT00    29160   Netting
XXXX Z4 AT00    -27000  Netting

1 个答案:

答案 0 :(得分:1)

根据您的规则和示例数据,以下内容应该有效:

select t.*,
       (case when exists (select 1
                          from t t2
                          where t2.entt = t.entt and t2.text = t.text and
                                t2.amount = -t.amount
                         )
             then 'Netting'
             when exists  (select 1
                          from t t2
                          where t2.entt = t.entt and t2.text = t.text and
                                t2.amount <> t.amount
                         ) 
             then 'Impossible Netting'
             else 'No Netting'
        end) as status
from t;