2014-12-02 69 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