2017-06-13 196 views
1

我想弄清楚如何在where子句中使用case語句(with!=),這裏是我想要做的事情的一個想法:CASE語句WHERE子句中!=條件

SELECT * 
FROM Table1 JOIN Table2 JOIN Table3 
WHERE 
    CASE @fruit 
    WHEN 'Apples' THEN (What would go here to return only data related to apples in Table1?) 
    WHEN 'Citrus' THEN (What would go here to return data related to either oranges or lemons in Table2?) 
    WHEN 'Other' THEN (return all data not related to apples, oranges, or lemons from all 3 tables) (!=) 
    END 

我在where子句中看到了case語句的幾個例子,但沒有一個帶有!=的條件。有任何想法嗎?

+0

你想實現什麼和SQL數據庫?如果你發佈你的數據和預期的輸出 – maSTAShuFu

+0

SQL Server將會很有幫助。我試圖通過從SSRS傳遞一個變量來過濾表格 – user3088720

+0

好吧......我可以說的是goodluck – maSTAShuFu

回答

1

如果我理解你的問題,你想評估其他布爾表達式除了平等。該CASE語句有兩種形式,即你想要一個(總是找平等)和這個其他形式:

CASE 
    WHEN <boolean expression> THEN <result expression> 
    WHEN <boolean expression> THEN <result expression> 
    ELSE <else expression> 
END 
2

簡單AND/OR組合會做:

SELECT * 
FROM Table 
WHERE 
    (@fruit != 'Other' AND Fruit = @fruit) OR 
    (@fruit = 'Other' AND Fruit NOT IN('Apples', 'Oranges') 
+0

我看到這是如何檢查變量與SSRS傳遞的內容,但我沒有看到它如何使用它來過濾數據(例如Table1.Fruit ='Apples') – user3088720

0

只是使用ELSE的一切

SELECT * 
FROM Table 
WHERE 
    CASE @fruit 
    WHEN 'Apples' THEN (What would go here to return only data related to apples?) 
    WHEN 'Oranges' THEN (What would go here to return only data related to oranges?) 
    ELSE (return all data not related to apples or oranges) (!=) 
    END 

或者您也可以使用參數的情況裏面,像這樣

SELECT * 
FROM Table 
WHERE 
    CASE 
    WHEN @fruit = 'Apples' THEN (What would go here to return only data related to apples?) 
    WHEN @fruit = 'Oranges' THEN (What would go here to return only data related to oranges?) 
    WHEN @fruit <> 'Apples' AND @fruit <> 'Oranges' THEN (return all data not related to apples or oranges) (!=) 
    END 
+0

感謝您的建議,我不認爲我的原始代碼很清楚我試圖完成的任務,爲了清晰我已經對其進行了編輯。 – user3088720

+0

@ user3088720我編輯了代碼,看看 – asmgx