簡體   English   中英

SQL 中關聯記錄計數的條件

[英]Condition on count of associated records in SQL

我有以下表格(帶有給定的列):

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

我想獲得所有(不同的)房屋和相關用戶的數量:

  • 至少有 1 個關聯的custom_value ,其中name列包含字符串“red”(不區分大小寫)並且 custom_value 列type值為“mandatory”。
  • 至少有 100 個關聯用戶,其狀態列為“活動”

如何在 PostgreSQL 中運行此查詢?

現在我有這個查詢(在Get records where associated records name contains a string AND associated record count is greater than threshold中得到了回答),但我也不知道如何 select 用戶數(:

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

您可以將子查詢轉換為橫向連接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM