Given scenario:
table fd
(cust_id, fd_id) primary-key and amount
table loan
(cust_id, l_id) primary-key and amount
I want to list all customers who have a fixed deposit with an amount less than the sum of all their loans.
Query:
SELECT cust_id
FROM fd
WHERE amount
<
(SELECT sum(amount)
FROM loan
WHERE fd.cust_id = loan.cust_id);
OR should we use
SELECT cust_id
FROM fd
WHERE amount
<
(SELECT sum(amount)
FROM loan
WHERE fd.cust_id = loan.cust_id group by cust_id);
A customer can have multiple loans but one FD is considered at a time.
GROUP BYcan be omitted in this case, because there is only (one) aggregate function(s) in theSELECTlist and all rows are guaranteed to belong to the same group ofcust_id( by theWHEREclause).The aggregation will be over all rows with matching
cust_idin both cases. So both queries are correct.This would be
a cleaneranother way to implement the same thing:There is one difference: rows with identical
(cust_id, amount)infdonly appear once in the result of my query, while they would appear multiple times in the original.Either way, if there is no matching row with a non-null
amountin tableloan, you get no rows at all. I assume you are aware of that.