![](/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.