'Where' 子句 T-SQL 中的条件 'Case When'

Conditional 'Case When' within 'Where' Clause T-SQL

我正在尝试在 where 语句中使用 case when 子句来 return 值,如果它们属于 2 个不同的类别。

到目前为止,这是我的代码:

 create view dbo.eightmonthinc
as
select *
from dbo.rentincreaseview 
where 
    case when [days same form] <= 9 
    then datediff(month, leasedate ,'2016-08-01 00:00:00') >= 8
    else datediff(month, rentlastchanged ,'2016-08-01 00:00:00') >= 12)
    end
go

这是我正在尝试做的事情的口头分解。

如果我的天数相同,公式 return 的值 <= 9 那么我只想 return 值,其中租赁日期和设定的未来日期之间的差值 >=8。

如果我天数相同的公式是 >9 那么我只想 return 值,其中租金上次更改日期和未来日期之间的差异是 >=12。

但是,我希望在同一个查询中 return 编辑两组数据。不幸的是,我一直收到 'incorrect syntax' 错误。

我还在学习,所以我有点不确定如何解决这个问题。任何帮助将不胜感激。

您不能使用这样的 case 语句(根据输入计算不同的布尔表达式),但您可以改用布尔 AND 和 OR 重写您的逻辑:

where 
    ([days same form] <= 9 and 
     datediff(month, leasedate ,'2016-08-01 00:00:00') >= 8)
    or 
    ([days same form] > 9 and 
     datediff(month, rentlastchanged ,'2016-08-01 00:00:00') >= 12))

可以 作为 case 语句做你想做的事,但它需要成为 datediff():

的参数
create view dbo.eightmonthinc as
select *
from dbo.rentincreaseview 
where ([days same form] <= 9 and datediff(month, leasedate, '2016-08-01') >= 8
      ) or
      ([days same form] > 9 and datediff(month, rentlastchanged, '2016-08-01') >= 12
      );

正确的逻辑需要在[days same form]上重复比较两次。此外,您不需要日期常量上的 hh:mm:ss。

我相信这就是您打算做的,尽管您可能会坚持接受的答案,因为这是更熟悉的形式。显然下面的技巧是嵌套 case 表达式。请记住,case 计算的是一个值,而不是条件,正如许多人试图做的那样。

select *
from dbo.rentincreaseview 
where 
    case when [days same form] <= 9 then
        case
            when datediff(month, leasedate ,'2016-08-01') >= 8 then 1
            when datediff(month, rentlastchanged ,'2016-08-01') >= 12) then 1
        end
    end
go

正如 Gordon 所暗示的那样,您可以尝试:

...
where
    datediff(
        month,
        case when [days same form] then leasedate else rentlastchanged end,
        '2016-08-01 00:00:00'
    ) 
      >=
    case when [days same form] <= 9 then 8 else 12 end

在某些情况下,这些表格可能很有用。大多数时候我怀疑这是个好主意。