我會做這樣的事情...(有數據樣本表變量包括)
DECLARE @TABLE TABLE (ContactID INT, Firstname VARCHAR(55), Lastname VARCHAR(55), Mobile VARCHAR(55));
INSERT INTO @TABLE VALUES (1, 'Emma', 'Watsan', '9991234567');
INSERT INTO @TABLE VALUES (2, 'Jhon', 'Wick', '8887654321');
INSERT INTO @TABLE VALUES (1, 'Emma', 'Watsan', '9990001111');
INSERT INTO @TABLE VALUES (1, 'Emma', 'Watsan', '9990001111');
SELECT
T1.FirstName + ' ' + T1.LastName AS Name
,T1.Mobile
,MAX(CASE WHEN T2.RowID IS NULL THEN 0 ELSE 1 END) AS Duplicate
FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY FirstName,LastName, Mobile) AS RowID
,*
FROM @TABLE
) T1
LEFT JOIN
(
SELECT
ROW_NUMBER() OVER (ORDER BY FirstName,LastName, Mobile) AS RowID
,*
FROM @TABLE
) T2
ON T1.ContactID = T2.ContactID
AND T1.Mobile = T2.Mobile
AND T1.RowID <> T2.RowID
GROUP BY T1.FirstName + ' ' + T1.LastName, T1.Mobile
;
如果實際的表已經有行號,比起row_number()
函數可以跳過並且在表中使用的表的實際行ID。
在這裏的例子中,Emma Watsan有兩次相同的號碼(故意使用),另一個號碼只在表格中顯示一次。重複的手機號碼被標記(Duplicate = 1
),但其他號碼不是,根據需要。
來源
2017-02-23 08:37:28
3BK
似乎只是更改爲'COUNT(DISTINCT Mobile)> 1' – Eric