Reputation: 797
I want to show the loans which are borrowed the least. This is a case where two loans are tied in the smallest number of borrowers.
Loan:
no | type
------------
L1 | house
L2 | student
L3 | car
Borrower ('num' is foreign key to 'no'):
name | num
----------
A | L1
A | L1
A | L2
A | L3
SELECT loan.type
FROM loan, borrower
WHERE loan.no = b.num
AND loan.type = (SELECT MIN(type) from loan)
GROUP BY loan.type
This should produce student
and car
but for now it's just giving me one of them. How should I modify my query to solve this?
Upvotes: 1
Views: 1468
Reputation: 1269873
Here is a method using a CTE:
WITH lb as (
SELECT l.type, COUNT(b.num) as cnt
FROM loan l LEFT JOIN
borrower b
ON l.no = b.num
GROUP BY l.type
)
SELECT lb.type
FROM lb
WHERE lb.cnt = (SELECT MIN(lb.cnt) FROM lb);
Notes:
LEFT JOIN
considers loan types with no borrowers.JOIN
syntax. Simple rule: Never use commas in the FROM
clause; always use explicit JOIN
syntax.Upvotes: 3