我有两个表(fruits
和fruitSales
),我的查询要求是:
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'
简而言之:我的查询中唯一的区别是query2中的“like”和query1中的“=”。在这种情况下我不知道如何使用CASE查询。(因为我的输入数据依赖于两个值,Apple或Banana)
非常感谢解决方案。
答案 0 :(得分: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';
答案 1 :(得分: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
答案 2 :(得分: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>
答案 3 :(得分: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'