2015-09-15 63 views
1

好的,我有這個小問題需要解決;我有兩個表格[Customers]和[Orders],它們通過CustomerID鏈接。這很容易通過每個客戶獲得訂單數()...SQL Server:顯示客戶列表的訂單數多於指定客戶的數量

SELECT c.CompanyName, COUNT(*) AS [Nbr of Orders] 
FROM [Orders] o 
INNER JOIN [Customers] c 
ON c.CustomerID = o.CustomerID 
GROUP BY c.CompanyName 

但是從問題的最後一部分來問題:我需要獲得該名單,但只有那些有多個訂單這些客戶(c.CompagnyName =「XYZ」) 我嘗試添加這樣的WHERE子句

WHERE COUNT(*) > (SELECT COUNT(*) 
        FROM [Orders] o 
        INNER JOIN [Customers] c 
        ON c.CustomerID = o.CustomerID 
        WHERE c.CompagnyName = 'XYZ') 

SQL錯誤:P 樣子可笑,但我知道,如果有人可以告訴我,我錯過!

+0

嘗試把周圍的評估聲明(計數括號(*)>(SELECT COUNT(*)FROM [常規] O INNER JOIN [客戶]ç ON c.CustomerID = o.CustomerID WHERE c.CompagnyName = 'XYZ')) – Dane

+0

我想你想HAVING子句而不是WHERE子句,因爲您正在過濾聚合函數。 –

+0

謝謝@TheDumbRadish,我只改變了在哪裏,並且工作很棒!阿夫,我不能大拇指評論:/ – BlinkSun

回答

1

看起來你可以使用having子句。所以,你的例子是 SELECT c.CompanyName, COUNT(*) AS [Nbr of Orders] FROM [Orders] o INNER JOIN [Customers] c ON c.CustomerID = o.CustomerID GROUP BY c.CompanyName having count(*) > 1

0

我想你想HAVING子句而不是WHERE子句,因爲你是在一個聚合函數過濾

相關問題