SQL Server计算列(如果值为负,则为0)

时间:2018-03-07 04:53:41

标签: sql-server-2016

我有一个计算的SQL Server列,其计算方式如下:

Number1 - Number2

如果碰巧这个数学等于负数,我想在字段中输入0而不是负数

IE:5-10 = -5(显示0)或仅为正数。

enter image description here

SELECT 
    CASE 
       WHEN [Scheduled] - [Purchased] < 0 
          THEN 0 
          ELSE [Scheduled] - [Purchased] 
    END

SELECT 
    IIF([Scheduled] - [Purchased] < 0, 0, [Scheduled] - [Purchased])

2 个答案:

答案 0 :(得分:3)

使用CASE

SELECT CASE WHEN Scheduled - Purchased < 0 THEN 0 ELSE Scheduled - Purchased END

如果用作计算列,只需写:

CASE WHEN Scheduled - Purchased < 0 THEN 0 ELSE Scheduled - Purchased END

SQL Server 2012起,您还可以使用IIF函数:

SELECT IIF(Scheduled - Purchased < 0, 0, Scheduled - Purchased)

答案 1 :(得分:0)

你必须在这里使用带有if else语句的sql查询 尝试使用以下statem,ents 或者参考 this article

DateTime