简体   繁体   中英

SQL query involving specific counts

person(id primary key, name)
money(acct primary key, loaner)
loan(id primary key, acct)

How would I create an SQL query that shows for each loaner the names of persons who took more than four loans from that specific loaner?

I tried count in the where clause but I am clueless so far.

you could use the HAVING clause. or write a subquery to get all the counts, and use WHERE count > 4 in the outer query

 SELECT p.id, p.name, m.loaner, COUNT(*) FROM person p 
   INNER JOIN loan l ON p.id = l.id
   INNER JOIN money m ON l.acct = m.acct
   GROUP BY id, name, lower
   HAVING COUNT(*) > 4

What this does is create an aggregated record set with one record for each combination of id, name, and lender (loaner) along with a count of how many times that combination occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM