2015-11-07 717 views
2

我當前有一個查詢,它返回每個客戶持有的帳戶總數,但是如何使其僅返回擁有多個帳戶的客戶?結果「大於或等於」的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

回答你的問題是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; 

這是簡單得多。

+0

第二joinless版本是唯一正確的,如果我們假設所有的「擁有」記錄「客戶」有一個父記錄。這看起來很直觀,但可能並非如此。 – JosephStyons

+0

@JosephStyons。 。 。他們都加入了'CustomerId',所以看起來這種關係非常合理。 –

+0

如果我在這裏猜測,「HAVING COUNT(*)> 1」語句查看整數大於1的行嗎? – Belphegor

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 
1

請嘗試

WHERE C.customerID = O.customerID AND count(O.accNumber) > 1 
相關問題