select語句返回位於獨特城市和州中的每個供應商的名稱,城市和州(即排除與另一個供應商具有相同城市和州的供應商)SQL Server - 相關子查詢/自加入
SELECT
VendorName, VendorCity, VendorState
FROM
Vendors
WHERE
VendorState + VendorCity NOT IN (SELECT VendorState + VendorCity
FROM Vendors
GROUP BY VendorState + VendorCity
HAVING COUNT(*) > 1)
ORDER BY
VendorState, VendorCity;
備選答案
SELECT
VendorName, VendorCity, VendorState
FROM
Vendors AS Vendors_Main
WHERE
VendorCity + VendorState NOT IN (SELECT VendorCity + VendorState
FROM Vendors AS Vendors_Sub
WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID)
ORDER BY
VendorState, VendorCity;
我明白了第一個答案,而不是替代查詢。混亂點:下面的行不會返回0行,因爲它們引用同一個表而沒有額外的where子句?
WHERE Vendors_Sub.VendorID <> Vendors_Main.VendorID)