2014-12-02 71 views
1

我有兩個表(fruitsfruitSales),那裏有我的查詢要求是:案例查詢值

if fruit = 'Apple' OR 'Banana' then fire (query1) else fire(query2) 

//即當我輸入的是蘋果或香蕉,然後QUERY1有火或其他查詢2。

這裏是我的兩個查詢:

查詢#1:

select a.*, b.quantity 
from fruits a 
left join fruitSales b on a.fruitPrice = '%'+b.fruitPrice+'%' 
where a.fruit = 'Apple' 

查詢#2:

select a.*, b.quantity 
from fruits a 
left join fruitSales b on a.fruitPrice like '%' + b.fruitPrice + '%' 
where a.fruit = 'Orange' 

總之:在我的查詢唯一的區別就是 「喜歡」 在查詢1中的query2和「=」。我不知道如何在這種情況下使用CASE查詢(因爲我的輸入數據依賴於Apple或Banana這兩個值)

解決方案非常感謝。

+0

爲什麼不試試if else then case語句在哪裏as if else else在某些場景中優化器會更好。 (@fruit ='Apple') 然後開始查詢........結束 if(@fruit ='Banana') 然後開始查詢........結束 – 2014-12-02 06:41:13

+0

可以我是這樣做的兩個輸入?如果(@水果=蘋果或@水果=香蕉)?像這樣的東西存在嗎? – HookUp 2014-12-02 06:42:50

+0

確實走了吧 – 2014-12-02 06:44:39

回答

0

使用CASE條件JOIN條件。

select a.*, b.quantity 
from fruits a 
left join fruitSales b on 
    CASE WHEN a.fruit IN ('Apple', 'Banana') 
        AND a.fruitPrice = '%'+b.fruitPrice+'%' 
     THEN 1 
     WHEN a.fruit NOT IN ('Apple', 'Banana') 
       AND a.fruitPrice like '%' + b.fruitPrice + '%' 
     THEN 1 
     ELSE 0 
    END = 1 
where a.fruit = 'Apple' 
+0

這工作..謝謝庫馬爾:) @所有..感謝您的答覆...我也會嘗試和學習其他答覆。 – HookUp 2014-12-02 06:57:24

0

試試這個:

SELECT a.*, b.quantity 
FROM fruits a 
LEFT JOIN fruitSales b ON a.fruitPrice LIKE (CASE WHEN a.fruit IN ('Apple', 'Banana') THEN b.fruitPrice ELSE CONCAT('%', b.fruitPrice, '%') END) 
WHERE a.fruit = 'Apple'; 
+0

nope我的意思是我的要求是基於LIKE或=過濾。即使(水果=蘋果或香蕉)結果應該是CONCAT('%',b.fruitPrice,'%')。但是= – HookUp 2014-12-02 06:45:39

+0

@CoolGurl您能澄清一下您正在查找的數據 – 2014-12-02 06:51:43

0
DECLARE @fruit varchar(50) 
SET @fruit = '' -- your value 
IF @fruit ='apple' OR @fruit = 'banana' 
BEGIN 
    SELECT a.*, b.quantity 
    FROM fruits a 
    LEFT JOIN fruitSales b ON a.fruitPrice LIKE '%'+b.fruitPrice+'%' 
    WHERE a.fruit = 'Apple' 
END 
ELSE 
BEGIN 
    SELECT a.*, b.quantity 
    FROM fruits a 
    LEFT JOIN fruitSales b ON a.fruitPrice LIKE '%' + b.fruitPrice + '%' 
    WHERE a.fruit = 'Orange' 
END 
+0

我應該使用商店程序來滿足這種要求嗎? – HookUp 2014-12-02 06:46:46

+0

取決於你是如何調用代碼 – Raj 2014-12-02 06:55:26

0

但爲什麼你需要的情況下查詢?

select a.*, b.quantity 
from fruits a 
left join fruitSales b on 
    (a.fruit in ('Apple', 'Banana') and a.fruitPrice = '%'+b.fruitPrice+'%') 
    or 
    (a.fruit not in ('Apple', 'Banana') and a.fruitPrice like '%'+b.fruitPrice+'%') 
where a.fruit = <your fruit> 
+0

雅我真的不需要的情況下。我想以簡單的方式解決它。但是您的查詢不適合我的要求。 – HookUp 2014-12-02 06:49:07

+0

我修改了查詢,以便它能正常工作。 – 2014-12-02 07:07:57