Reputation: 95
I have a table named '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.
I tried the sql query-
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. Can anyone help me with a sql query which can achieve this ?
Upvotes: 1
Views: 2359
Reputation: 1029
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;
Upvotes: 0
Reputation: 198
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)
Upvotes: 2
Reputation: 12025
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
);
Upvotes: 1
Reputation: 72185
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)
Upvotes: 2