我需要根据某种优先级从表中选择数据,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
也就是说,如果我找到3个基于价格的产品project = X,我不想选择customer = Y.我只想返回结果3行并完成.
你怎么在SQL中做这样的事情?对pseudo-if使用某种CASE语句?做工会还是其他聪明的事情?
编辑:我正在使用MS SQL.
谢谢!
Ale*_*lex 103
您可以进行以下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
Run Code Online (Sandbox Code Playgroud)
Roh*_*hit 31
CASE语句最接近SQL中的IF语句,并且在所有版本的SQL Server上都受支持:
SELECT CASE <variable>
WHEN <value> THEN <returnvalue>
WHEN <othervalue> THEN <returnthis>
ELSE <returndefaultcase>
END
FROM <table>
Run Code Online (Sandbox Code Playgroud)
And*_*eev 17
而不是使用EXISTS,COUNT只是使用@@ROWCOUNT:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
360934 次 |
| 最近记录: |