2016-06-30 482 views
0

我試圖在when語句中使用when子句來返回值,如果它們屬於2個不同的類別。'Where'子句中的條件'Case When'T-SQL

這是我到目前爲止的代碼:

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 

這裏是一個口頭上休息的我試圖做下來。

如果我的天數相同的公式返回值< = 9,那麼我只想返回租賃日期與設定的未來日期之間的差異> = 8時的值。

如果我的日子相同的公式大於9,那麼我只想返回最後一次更改日期與未來日期之間的差額大於等於12的值。

但是,我希望在同一個查詢中返回兩組數據。不幸的是,我不斷收到'錯誤的語法'錯誤。

我還在學習,所以我有點不確定如何解決這個問題。任何幫助將不勝感激。

+0

我在我的答案中修正了一個邏輯錯誤 - 請檢查一下 - 舊版本會產生錯誤的結果。感謝Gordon Linoff,他的答案指出了錯誤。 – Blorgbeard

回答

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

可以做什麼你想作爲一個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 
    ); 

正確的邏輯需要重複上比較兩次。另外,你不需要日期常量上的hh:mm:ss。

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 

有一些情況下,這些形式可以證明是有用的。大多數時候我懷疑這是個好主意。