簡體   English   中英

如果結果計數大於一,如何添加條件

[英]How to add where condition if result count is greater than one

我想建立返回唯一ID的SQL查詢。 我的問題是,如果我有多個結果,則需要添加另一條件來查詢。

select u.id
from users u
where u.id in ('1','2','3')
and u.active = 'Y'

如果我得到多個結果,則需要添加:

and u.active_contact = 'Y'

我試圖建立這個查詢

select * from (
select u.id, count(u.id) as results
from users u
where u.id in ('1','2','3')
and u.active = 'Y'
group by u.id
) tab
If(tab.results > 1) then
    where tab.u.active_contact = 'Y'
end

提前致謝。

希望我對自己的自我解釋足夠好。

這是另一種方法:

SELECT id
  FROM (SELECT id, (CASE WHEN active ='Y' THEN 1 ELSE 0 END) + (CASE WHEN active_contact ='Y' THEN 1 ELSE 0 END) as actv FROM users ORDER BY actv DESC)
  WHERE actv > 0
  LIMIT 1

子查詢添加了一個匯總activeactive_contact的列。 然后,主SELECT優化這兩個字段的組合,至少需要其中之一。 我相信這可以提供預期的結果。

解決此問題的可能方法中,有兩種。

1)使用active_contact ID。 如果沒有,請使用另一個ID。

select coalesce( max(case when active_contact = 'Y' then id end), max(id) ) as id
from users
where id in ('1','2','3')
and active = 'Y';

2)排序,其中active_contact排名第一。 然后獲得第一條記錄。

select id
from
(
  select id
  from users
  where id in ('1','2','3')
  and active = 'Y'
  order by case when active_contact = 'Y' then 1 else 2 end
) where rownum = 1;

一種使用解析函數的方法

SELECT id
FROM (SELECT u.id
           , u.active_contact
           , count(*) OVER () actives
      FROM users u
      WHERE u.id IN ('1','2','3')
      AND u.active = 'Y')
WHERE (  actives = 1
      OR (   actives > 1
         AND active_contact = 'Y'))

如果有多個記錄,其中active = 'Y' AND active_contact = 'Y' ,則將全部返回。 如果只需要其中之一,則需要確定選擇該標准的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM