你可以在SQL中有if-then-else逻辑吗?

我需要根据某种优先级从表中select数据,如下所示:

select product, price from table1 where project = 1 -- pseudo: if no price found, do this: select product, price from table1 where customer = 2 -- pseudo: if still no price found, do this: select product, price from table1 where company = 3 

也就是说,如果我发现3个产品的价格基于project = X ,我不想selectcustomer = Y 我只是想返回结果3行并完成。

你如何在SQL中做这样的事情? 使用某种CASE语句作为伪if? 做一个工会或其他聪明的事情?

编辑:我正在使用MS SQL。

谢谢!

您可以进行以下sql查询

 IF ((SELECT COUNT(*) FROM table1 WHERE project = 1) > 0) SELECT product, price FROM table1 WHERE project = 1 ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 2) > 0) SELECT product, price FROM table1 WHERE project = 2 ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 3) > 0) SELECT product, price FROM table1 WHERE project = 3 

CASE语句最接近SQL中的IF语句,并且在所有版本的SQL Server上都受支持:

 SELECT CASE <variable> WHEN <value> THEN <returnvalue> WHEN <othervalue> THEN <returnthis> ELSE <returndefaultcase> END FROM <table> 

使用@@ROWCOUNT代替EXISTSCOUNT

 select product, price from table1 where project = 1 IF @@ROWCOUNT = 0 BEGIN select product, price from table1 where customer = 2 IF @@ROWCOUNT = 0 select product, price from table1 where company = 3 END 

请检查是否有帮助:

 select TOP 1 product, price from table1 where (project=1 OR Customer=2 OR company=3) AND price IS NOT NULL ORDER BY company 

使用SQL服务器,您可以使用CTE而不是IF / THEN逻辑,以便轻松映射现有查询并更改涉及的查询数;

 WITH cte AS ( SELECT product,price,1 a FROM table1 WHERE project=1 UNION ALL SELECT product,price,2 a FROM table1 WHERE customer=2 UNION ALL SELECT product,price,3 a FROM table1 WHERE company=3 ) SELECT TOP 1 WITH TIES product,price FROM cte ORDER BY a; 

一个SQLfiddle用来testing 。

或者,您可以将其全部组合到一个SELECT以简化优化程序;

 SELECT TOP 1 WITH TIES product,price FROM table1 WHERE project=1 OR customer=2 OR company=3 ORDER BY CASE WHEN project=1 THEN 1 WHEN customer=2 THEN 2 WHEN company=3 THEN 3 END; 

另一个SQLfiddle 。

有一个案例陈述,但我认为下面是更准确/有效/更容易阅读你想要的。

 select product ,coalesce(t4.price,t2.price, t3.price) as price from table1 t1 left join table1 t2 on t1.product = t2.product and t2.customer =2 left join table1 t3 on t1.product = t3.product and t3.company =3 left join table1 t4 on t1.product = t4.product and t4.project =1 

– 大部分与上述类似的答案。 代码包括testing

 DROP TABLE table1 GO CREATE TABLE table1 (project int, customer int, company int, product int, price money) GO INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75) GO SELECT TOP 1 WITH TIES product , price , CASE WhereFound WHEN 1 THEN 'Project' WHEN 2 THEN 'Customer' WHEN 3 THEN 'Company' ELSE 'No Match' END AS Source FROM ( SELECT product, price, 1 as WhereFound FROM table1 where project = 11 UNION ALL SELECT product, price, 2 FROM table1 where customer = 0 UNION ALL SELECT product, price, 3 FROM table1 where company = 30 ) AS tbl ORDER BY WhereFound ASC