简体   繁体   中英

SQL COUNT function for results “greater than or equal to”

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

The answer to your question is HAVING . However, you need to learn to use proper JOIN 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.

Add a HAVING clause

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

请试试

WHERE C.customerID = O.customerID AND count(O.accNumber) > 1 

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