PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Condizione sul conteggio di record associati in SQL

Puoi trasformare la sottoquery in una lateral join:

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'
  )

La LATERAL permette di calcolare il conteggio degli utenti per ogni casa e di filtrare poi il risultato in un'unica scansione.