如何将负值转换为零

时间:2015-06-25 05:46:19

标签: sql sql-server sql-server-2008

    SELECT  name ,
        ( SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount
                   ELSE 0
              END) - SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount
                              ELSE 0
                         END) ) * 5 / 100 AS Interest
    FROM .....

此查询返回一些负值,我想将负值转换为零。 如何编写查询

4 个答案:

答案 0 :(得分:5)

这样的事可能吗?

SELECT t1.name AS Name, CASE WHEN t1.Interest > 0 THEN Interest ELSE 0 END AS Interest
FROM (select name, (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount else 0 end)) *5/100 as Interest from ...........) as t1

答案 1 :(得分:3)

使用第二个案例陈述:

redirect

如果你不回报什么是否定的:

select name, (sum(case when TransTypeName like 'credit%' then (case when amount>0 then amount else 0 end;) else 0 end) -
sum(case when TransTypeName like 'Debit%' then (case when amount>0 then amount else 0 end;) else 0 end)) *5/100 as Interest
from ...........

答案 2 :(得分:1)

对于那些只喜欢短线而不是长CASE语句的人。

使用isnull(nullif(sign({column name}),-1),0)

select isnull(nullif(sign(-100),-1),0) as negative
select isnull(nullif(sign(0),-1),0) as zero
select isnull(nullif(sign(100),-1),0) as positive

答案 3 :(得分:0)

SELECT t1.name AS Name, CASE WHEN t1.Interest > 0 THEN Interest ELSE 0 END AS Interest
FROM (select name, (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount else 0 end)) *5/100 as Interest from ...........) as t1