Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL COUNT function for results "greater than or equal to"

Tags:

sql

count

I currently have a query where it returns the total number of accounts each customer holds, but how do I make it so that it returns only customers who has more than 1 account?

SELECT C.customerID, COUNT(O.accNumber) AS "total"
FROM Customer C, Owns O
WHERE C.customerID = O.customerID
GROUP BY C.customerID
like image 846
Belphegor Avatar asked Dec 24 '22 12:12

Belphegor


1 Answers

The answer to your question is HAVING. However, you need to learn to use properJOIN syntax. Simple rule: Never use a comma in the FROM clause. Always use explicit JOIN syntax.

SELECT C.customerID, COUNT(O.accNumber) AS total
FROM Customer C JOIN
     Owns O
     ON C.customerID = O.customerID
GROUP BY C.customerID
HAVING COUNT(*) > 1;

Actually, you don't even need the JOIN:

SELECT o.customerID, COUNT(o.accNumber) AS total
FROM Owns o
GROUP BY o.customerID
HAVING COUNT(*) > 1;

That's much simpler.

like image 151
Gordon Linoff Avatar answered Dec 27 '22 05:12

Gordon Linoff