【发布时间】:2015-11-07 04:21:25
【问题描述】:
我目前有一个查询,它返回每个客户持有的帐户总数,但我如何使它只返回拥有超过 1 个帐户的客户?
SELECT C.customerID, COUNT(O.accNumber) AS "total"
FROM Customer C, Owns O
WHERE C.customerID = O.customerID
GROUP BY C.customerID
【问题讨论】:
我目前有一个查询,它返回每个客户持有的帐户总数,但我如何使它只返回拥有超过 1 个帐户的客户?
SELECT C.customerID, COUNT(O.accNumber) AS "total"
FROM Customer C, Owns O
WHERE C.customerID = O.customerID
GROUP BY C.customerID
【问题讨论】:
您的问题的答案是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;
这要简单得多。
【讨论】:
CustomerId,所以看起来关系很好。
COUNT(*) > 1 表示每个组有不止一行。由于*,它没有查看任何特定列。
添加 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
【讨论】:
请尝试
WHERE C.customerID = O.customerID AND count(O.accNumber) > 1
【讨论】: