有条件的情况当'在'哪里'条款T-SQL

时间:2016-06-30 23:51:39

标签: sql-server case where

我试图在where语句中使用case when子句来返回值,如果它们分为两个不同的类别。

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

 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

这是对我要做的事情的口头细分。

如果我的日期相同的公式返回一个值&lt; = 9,那么我只想返回租约日期和设定的未来日期之差为&gt; = 8的值。

如果我的日子相同公式> 9,那么我只想返回租金上次更改日期和未来日期之间的差值为> = 12的值。

但是,我希望在同一查询中返回两组数据。不幸的是,我一直在弄错“##;错误。

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

3 个答案:

答案 0 :(得分:1)

你不能像这样使用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))

答案 1 :(得分:1)

可以做你想要的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。

答案 2 :(得分:0)

我相信这是你打算做的事情,尽管你可能会坚持接受的答案,因为那是比较熟悉的形式。显然,下面的技巧是嵌套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

正如戈登所暗示的那样,你可以试试:

...
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

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

相关问题