结果的SQL COUNT函数"大于或等于"

时间:2015-11-07 04:21:25

标签: sql count

我目前有一个查询,它返回每个客户持有的帐户总数,但我该如何制作,以便只返回拥有多个帐户的客户?

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

3 个答案:

答案 0 :(得分:4)

您的问题的答案是HAVING。但是,您需要学习使用正确的JOIN语法。简单规则:从不FROM子句中使用逗号。 始终使用明确的JOIN语法。

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;

实际上,您甚至不需要JOIN

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

这简单得多。

答案 1 :(得分:3)

添加HAVING子句

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

答案 2 :(得分:1)

请尝试

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