你能在 SQL 中有 if-then-else 逻辑吗? [英] Can you have if-then-else logic in SQL?
本文介绍了你能在 SQL 中有 if-then-else 逻辑吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据某种优先级从表中选择数据,如下所示:
I need to do select data from a table based on some kind of priority like so:
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
,我不想在 customer = Y
上选择.我只想返回结果 3 行并完成.
That is, if I found 3 products with prices based on project = X
, I don't want to select on customer = Y
. I just want to return the resulting 3 rows and be done.
你应该如何在 SQL 中做这样的事情?对伪 if 使用某种 CASE 语句?做一个工会或其他一些聪明的事情?
How are you supposed to do stuff like this in SQL? Use some kind of CASE-statement for the pseudo-if's? Do a union or some other smart thing?
我使用的是 MS SQL.
I'm using MS SQL.
谢谢!
推荐答案
可以进行如下sql查询
You can make the following sql query
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
这篇关于你能在 SQL 中有 if-then-else 逻辑吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文