【问题标题】:If statement based on other column基于其他列的 if 语句
【发布时间】:2016-03-10 06:58:59
【问题描述】:

我有一个选择语句:

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)

感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    使用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 必须是相同的数据类型。

    【讨论】:

      【解决方案2】:

      使用 SQL Server 2012 支持的 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
      

      【讨论】:

      • iif 只是 case 表达式的语法糖 - 请参阅 msdn page. 中的备注部分当然,这个解决方案可以正常工作。
      【解决方案3】:

      这样试试,

      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
      

      【讨论】:

      • 这正是我使用 cte 的原因 - 只写一次 datediff。当然,这个解决方案可以正常工作。
      • @Zohar Peled:你的代码看起来不错。我想让它易于理解但冗长。
      猜你喜欢
      • 1970-01-01
      • 2020-07-09
      • 2014-02-14
      • 1970-01-01
      • 2015-09-07
      • 2021-05-04
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      相关资源
      最近更新 更多