Condition on count of associated records in SQL

独自空忆成欢 提交于 2020-06-28 04:01:18

问题


I have the following tables (with given columns):

houses (id)
users (id, house_id, active)
custom_values (name, house_id, type)

I want to get all the (distinct) houses and the count of associated users that:

  • have at least 1 associated custom_value which name column contains the string 'red' (case insensitive) AND the custom_value column type value is 'mandatory'.
  • have at least 100 associated users which status column is 'active'

How can I run this query in PostgreSQL?

Right now I have this query (which was answered in Get records where associated records name contain a string AND associated record count is bigger than threshold), but I don't know how to select the count of users too (:

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

回答1:


You can turn the subquery to a 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'
    )


来源:https://stackoverflow.com/questions/61750016/condition-on-count-of-associated-records-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!