![](/img/trans.png)
[英]SQL Server : ISNULL(compound NULL condition, 'a string') returns only the 1st character, under certain circumstance(s)
[英]SQL returns only for 1st TRUE condition
我有一个简单的查询,如果第一个条件为真,我只想返回一个值。
查询如下所示:
SELECT * FROM table
WHERE case column
when val1 then 1
when val2 then 1
when val3 then 1
end = 1
在表中,可以是所有值(val1、val2 和 val3)的行,但不是强制性的,我只想返回条件为真的第一行并放弃其余条件。
对于我的 SQL 版本,select 语句返回所有 TRUE 条件的行。
你能帮我吗。
据我了解您的要求:您可以根据不同的条件找到匹配项。 您只想返回最匹配的行。
一个典型的例子是一个设置表,它可以包含一个国家、城市甚至地区的设置。 如果可用,您需要地区设置,否则需要城市设置,并且只有在此设置不可用时,您才会满足于全球国家/地区设置。
对于此类排名,您可以使用ROW_NUMBER
。 即您对行进行编号,给出最佳匹配#1、第二最佳#2,等等。然后您只保持排在#1 的行。
select *
from
(
select
s.*,
row_number()
over (order by case
when s.country = :country
and s.city = :city
and s.district = :district then 1
when s.country = :country
and s.city = :city then 2
else 3
end) as rn
from settings s
where s.country = :country
)
where rn = 1;
在你的例子中:
select *
from
(
select
t.*,
row_number()
over (order by case column when val1 then 1 when val2 then 2 else 3 end) as rn
from table t
where column in (val1, val2, val3)
)
where rn = 1;
如果可以有关系,即如果至少有一行与 val1 匹配,则显示所有与 val1 匹配的行,等等,然后使用RANK
或DENSE_RANK
而不是ROW_NUMBER
。
从 Oracle 12c 开始,您还可以使用FETCH
子句:
select *
from table
where column in (val1, val2, val3)
order by row_number()
over (order by case column when val1 then 1 when val2 then 2 else 3 end)
fetch first row only;
同样,如果您想允许DENSE_RANK
,请使用RANK
或DENSE_RANK
并将FETCH FIRST ROW ONLY
替换为FETCH FIRST ROW WITH TIES
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.