如果声明基于其他列

时间:2016-03-10 06:58:59

标签: sql sql-server datetime if-statement switch-statement

我有一个选择声明:

select DATEDIFF(day,[Contract Start Date],[Contract End Date]) as contract_time
from table 1

现在,如何添加到下一列if语句:

contract_time >= 390 then display A
contract_time < 390 then display B
contract_time is null display C? (because Contract start date or End date can be null)

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

使用case expression

;With cte as 
(
select DATEDIFF(day,[Contract Start Date],[Contract End Date]) as contract_time,
a,
b,
c
from table 1
)

select contract_time
       case when contract_time is null then c
            when contract_time >= 390 then a
            when contract_time <  390 then b
       end as otherColumn
from cte

请注意,a,b和c必须是所有相同的数据类型。

答案 1 :(得分:0)

使用在SQL Server 2012中支持的IIF功能,否则您也可以使用CASE WHEN ...那么......结束

;With cte_table1 as 
(
   SELECT 
       DATEDIFF(day,[Contract Start Date],[Contract End Date]) as contract_time,
       A,
       B,
       C
   FROM [table 1]
)

SELECT contract_time,
       IIF(contract_time is null,C,
           IIF(contract_time >= 390, A,B))
       as otherColumn
FROM cte_table1

答案 2 :(得分:0)

试试这个,

SELECT DATEDIFF(day, [Contract Start Date], [Contract End Date]) AS contract_time
    ,CASE 
        WHEN DATEDIFF(day, [Contract Start Date], [Contract End Date]) IS NULL
            THEN c
        WHEN DATEDIFF(day, [Contract Start Date], [Contract End Date]) >= 390
            THEN a
        WHEN DATEDIFF(day, [Contract Start Date], [Contract End Date]) < 390
            THEN b
        END AS otherColumn
FROM TABLE