【问题标题】:Case query based on two input values基于两个输入值的案例查询
【发布时间】:2015-01-30 08:06:27
【问题描述】:

我有两个表(fruits 和 fruitSales),我的查询要求是:

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

// 即,当我的输入是苹果或香蕉时,query1 必须触发,否则 query2。

这是我的两个查询:

查询 #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'

简而言之:我的查询中的唯一区别是 query2 中的“like”和 query1 中的“=”。在这种情况下,我不知道如何使用 CASE 查询。(因为我的输入数据依赖于两个值,Apple 或 Banana)

非常感谢您的解决方案。

【问题讨论】:

  • 为什么你不尝试 if else then case 语句 where as if else 在某些情况下被优化器处理得更好。 if (@fruit ='Apple' ) then begin your query ........ end if (@fruit ='Banana' ) then begin your query ........ end
  • 我可以为两个输入做到这一点吗?如果(@fruit =Apple 或 @fruit=Banana)?这样的事情存在吗?

标签: sql sql-server select case sql-like


【解决方案1】:

但为什么需要案例查询?

 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> 

【讨论】:

  • 是的,我真的不需要案例。我想以一种简单的方式解决它。但是您的查询不符合我的要求。
【解决方案2】:

在JOIN 条件中使用CASE 条件。

 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' 

【讨论】:

  • 这行得通..谢谢库马尔:) @All..谢谢您的回复...我也会尝试学习其他回复。
【解决方案3】:
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

【讨论】:

  • 我应该使用商店程序来满足这种要求吗?
【解决方案4】:

试试这个:

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';

【讨论】:

  • 不,我的意思是我的要求是根据 LIKE 或 = 进行过滤。即使(fruit=Apple orbanana) 结果应该是 CONCAT('%', b.fruitPrice, '%')。但有 =
  • @CoolGurl 你能用你正在寻找的数据澄清一下吗
猜你喜欢
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2015-06-17
  • 1970-01-01
相关资源
最近更新 更多