SQL Query that relies on COUNT from another table? - SQLAlchemy

痞子三分冷 提交于 2021-01-28 22:23:30

问题


I need a query that can return the records from table A that have greater than COUNT records in table B. The query needs to be able to go in line with other filters that might be applied on table A.

Example case study:

I have a person and appointments table. I am looking for all people who have been in for 5 or more appointments. It must also support extra filter statements on the person table, such as age > 18.

EDIT -- SOLUTION

subquery = db.session.query(Appointment.id_person, 
                            func.count('*').label('person_count')) \
                     .group_by(Appointment.id_person).subquery()
qry = db.session.query(Person) \
                .outerjoin((subquery, Person.id == subquery.c.id_person)) \
                .order_by(Person.id).filter(subquery.c.person_count >= 5).filter(Person.dob <= '1992-10-29')

回答1:


Use a subquery:

SELECT * from person
WHERE PersonID IN 
  (SELECT PersonId FROM appointments
   GROUP BY PersonId
   HAVING COUNT(*) >= 5)
AND dob > 25



回答2:


SELECT Person.PersonID, Person.Name
FROM Person INNER JOIN Appointment
ON Person.PersonID = Appointment.PersonID
GROUP BY Person.PersonID, Person.Name
HAVING COUNT(Person.PersonID) >= 5


来源:https://stackoverflow.com/questions/4057223/sql-query-that-relies-on-count-from-another-table-sqlalchemy

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