简体   繁体   English

SQL查询以获取唯一列表

[英]SQL Query to get unique list

I have a table named 'resources' 我有一个名为“ resources”的表

Machine     Host        Enabled
mach1       host1       TRUE
mach2       host1       FALSE
mach3       host1       FALSE
mach4       host2       TRUE
mach5       host2       TRUE

I want to get the list of hosts where Enabled is True for all the resources/machines associated with them. 我想获取与之关联的所有资源/机器的Enabled为True的主机列表。

I tried the sql query- 我尝试了sql查询-

select distinct Host from resources where Enabled = TRUE;

But that query gives me back both host1 and host2 as the answer whereas I am expecting the answer to be just host2. 但是该查询使我同时返回了host1和host2作为答案,而我希望答案仅为host2。 Can anyone help me with a sql query which can achieve this ? 任何人都可以通过可以实现此目的的sql查询来帮助我吗?

Try this: 尝试这个:

SELECT Host
FROM resources
GROUP BY Host        
HAVING COUNT(*) = COUNT(CASE WHEN Enabled = True THEN 1 END)

or: 要么:

SELECT DISTINCT Host 
FROM resources AS r1
WHERE Enabled = TRUE AND 
      NOT EXISTS (SELECT 1 
                  FROM resources AS r2
                  WHERE r1.Host = r2.Host AND r2.enabled = FALSE)

TRY THIS ONE AND LET ME KNOW. 尝试一下,让我知道。

SELECT DISTINCT(Host)
FROM Resources
WHERE Enabled = TRUE AND Host NOT IN (Select Host FROM Resources WHERE Enabled = FALSE)

Try 尝试

select distinct Host from resources res1 where not exist (
   select 1 from resources res2 WHERE res1.host = res2.host AND Enabled = FALSE limit 1
);

This works too 这也有效

select host from resources e
having count(e.host)=(select count(enebled) from resources 
                    where enebled='TRUE' and host = e.host)
group by host;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM