2016-03-10 141 views
1

声明我有一个select语句:如果基于其他列

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

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

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) 

感谢您的帮助!

回答

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必须是全部相同的数据类型。它支持SQL Server 2012中

+0

感谢快速反应! – 4est

+0

很高兴帮助:-) –

0

使用IIF功能,否则你也可以使用CASE WHEN ... THEN ... END

;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 
+0

iif只是case语句的语法糖 - 请参阅其[msdn page。](https://msdn.microsoft.com/zh-cn/library/hh213574.aspx)中的备注部分当然,这个解决方案可以正常工作。 –

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 
+0

这正是我使用cte的原因 - 只写了一次'datediff'。当然,这个解决方案可以正常工作。 –

+0

@Zohar Peled:你的代码看起来不错。我想让它容易理解但冗长。 – StackUser