[英]SQL Select query when a condition is met
Site Owner | Site URL | Delete Site
User #1 | google.com | Yes
User #2 | google.com | Yes
User #3 | yahoo.com | No
User #4 | yahoo.com | Yes
User #5 | hotmail.com | No
User #6 | hotmail.com | NULL
我需要選擇所有站點所有者都回答“是”的所有站點URL。 如果來自同一站點URL的一個用戶回答“是”,而另一個回答“否”,則我不需要這些用戶。 因此,舉例來說,在上述示例中,我需要獲取google.com來使兩個用戶都回答“是”。
您可以使用group by
並having
:
select site_url
from t
group by site_url
having min(delete_site) = 'yes' and max(delete_site) = 'yes' and
count(*) = count(delete_site); -- no NULL values;
您實際上可以將having
子句簡化為:
having count(*) = sum(case when delete_site = 'yes' then 1 else 0 end)
這是執行此操作的另一個版本。 對於null值,我更喜歡使用ISNULL替換器,並且IIF用於解碼是否對可數數
SELECT
[Site Url]
FROM
Table1
GROUP BY
[Site Url]
HAVING
SUM( IIF(ISNULL([Delete Site], '')='Yes', 0, 1)) = 0
以簡單的方式,您還可以使用not exists
select *
from table t
where not exists (
select 1 from table
where [Site URL] = t.[Site URL] and [Delete Site] <> 'Yes'
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.