幾乎相同的答案VKP爲COUNT(*),但我更喜歡它作爲公共表格表達。
;WITH cte AS (
SELECT
*
,COUNT(*) OVER (PARTITION BY AddressLine) as RecordsAtAddress
FROM
TableName
)
SELECT *
FROM
cte
WHERE
RecordsAtAddress = 1
不過,我也想添加ROW_NUMBER窗函數來顯示你如何可以隨時選擇每個AddressLine的記錄。因此,在這種情況下,您將獲得1條重複記錄,而不是將它們排除在一起。
;WITH cte AS (
SELECT *
,ROW_NUMBER() OVER (PARTITION BY AddressLine ORDER BY CName) as RowNum
FROM
TableName
)
SELECT *
FROM
cte
WHERE
RowNum = 1
是因人而異謹慎使用IN或NOT IN尤其是與自由形式的文字是這樣,因爲如果AddressLine可以爲NULL,你不會得到你所期望的!性能通常也不是很好。 NOT IN vs NOT EXISTS
對於EXISTS或NOT EXISTS回答你居然還要涉及您的子查詢這樣的事情,注意不是存在,則可能對於這樣的情況下有更好的表現:
SELECT *
FROM
TableName t1
WHERE
NOT EXISTS (SELECT
t2.AddressLine
FROM
TableName t2
WHERE
t1.AddressLine = t2.AddressLine
GROUP BY
t2.AddressLine
HAVING COUNT(*) > 1)
所以,你排除兩行或你需要其中之一?在那種情況下,這個約翰? – Horaciux