PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Condizione sul conteggio dei record associati in SQL

Puoi trasformare la sottoquery in un join laterale:

select h.*, u.no_users
from houses h
cross join lateral (
    select count(*) no_users
    from users u 
    where u.house_id = h.house_id and u.status = 'active'
) u
where 
    u.cnt >= 100
    and exists (
        select 1 
        from custom_values cv 
        where cv.house_id = h.house_id and cv.type = 'mandatory' and lower(cv.name) = 'red'
    )