爲什麼兩個查詢的結果相同? (我使用Northwind數據庫)使用DISTINCT關鍵字時,爲什麼不會更改此查詢結果?
SELECT ContactTitle
, COUNT(CustomerID) AS NumberOfCustomer
FROM dbo.Customers
WHERE ContactTitle LIKE '%sales%'
GROUP BY ContactTitle
HAVING COUNT(*) >= 5
ORDER BY NumberOfCustomer desc
和
SELECT
DISTINCT ContactTitle
, COUNT(CustomerID) AS NumberOfCustomer
FROM dbo.Customers
WHERE ContactTitle LIKE '%sales%'
GROUP BY ContactTitle
HAVING COUNT(*) >= 5
ORDER BY NumberOfCustomer desc
結果是:
ContactTitle NumberOfCustomer
--------------------- ----------------
Sales Representative 17
Sales Manager 11
Sales Associate 7
Sales Agent 5
在我自己的理解,第二個查詢得到不同的標題和計算它的記錄,所以我期待結果將是沒有,因爲每個標題只有記錄計數爲1。
正確,除* *「在ContactTitle列上添加DISTINCT」*。 「DISTINCT」應用於整行,而不是列。 –
謝謝你的插圖。你如何理解查詢執行計劃? – SkyDrive
這裏的小故事(無恥廣告):[SELECT:order or processing](http://stackoverflow.com/questions/6545664/using-case-expression-column-in-where-clause/6545685#6545685) –