丢弃匹配的行并保留不匹配的行T-SQL

时间:2019-05-16 02:41:05

标签: sql-server tsql rows matching

我有一个数据集,并试图提出一个SQL查询以保留不匹配的行并丢弃匹配的行。

X_ID    Y_ID    Client_Id   User_Id date    
-------------------------------------------------------------
NULL    3000547 10000593    2001284 2019-03-11 10:59:21.214 X_ID <> Y_ID for Same Client_ID & User_ID so I want to keep these records.
NULL    3000547 10000593    2001284 2019-03-11 10:45:09.022 
NULL    3000547 10000593    2001284 2019-03-11 19:29:30.028 
NULL    3000547 10000593    2001284 2019-03-11 19:29:45.168 
NULL    3000547 10000593    2001284 2019-03-11 11:06:12.072 
NULL    NULL    10000622    2000576 2019-03-27 09:33:42.995 
NULL    NULL    10000622    2000576 2019-03-27 09:34:04.495 
NULL    NULL    10000622    2000576 2019-03-27 15:53:48.794 
NULL    NULL    10000622    2018815 2019-03-27 10:37:01.250 
4000954 4000954 10157846    2017957 2019-03-11 13:44:54.469 X_ID = Y_ID for Same Client_ID & User_ID so I want to discard these records.
4000954 4000954 10157846    2017957 2019-03-11 13:30:35.101 
4000954 4000954 10157846    2017957 2019-03-11 13:33:23.738 
4000954 4000954 10157846    2017957 2019-03-14 16:25:24.684 
4000954 4000954 10157846    2017957 2019-03-14 16:25:24.684 
4000954 4000954 10157846    2017957 2019-03-14 16:25:24.684 
4000954 4000954 10157846    2017957 2019-03-14 08:52:32.047 
4000954 4000954 10157846    2017957 2019-03-27 15:02:30.867 
4000954 4000954 10462731    2017957 2019-03-27 15:57:12.415 
4000954 NULL    10761202    2017957 2019-03-29 12:36:16.546 X_ID <> Y_ID for Same Client_ID & User_ID so I want to keep these records.
NULL    4000954 10792367    2000876 2019-03-25 16:22:33.457 
NULL    4000954 10792367    2001469 2019-03-29 13:54:25.354 
4000954 NULL    12312028    2017957 2019-03-29 12:35:47.140 
4000954 4000761 12642798    2017957 2019-03-25 16:18:19.522 There is one match of X_ID = Y_ID for same Clieny_ID & User_ID so I want to discard all three rows. 
4000954 4000954 12642798    2017957 2019-03-25 16:18:19.522 
4000954 4000954 12642798    2017957 2019-03-25 16:18:19.522 
4000954 4000761 12642798    2017957 2019-03-25 16:18:19.522 All the rows X_ID <> Y_ID for Same Client_id & User_ID so I want to keep these records
4000954 4000762 12642798    2017957 2019-03-25 16:18:19.522 
4000954 4000763 12642798    2017957 2019-03-25 16:18:19.522

2 个答案:

答案 0 :(得分:1)

;WITH CTE AS 
(
    SELECT Distinct Client_ID, User_ID
    FROM [Your_Table]
    WHERE X_ID = Y_ID
)

SELECT *
FROM [Your_Table] AS T
LEFT OUTER JOIN CTE AS C
    ON T.Client_ID = C.Client_ID
    AND T.User_ID = C.User_ID
WHERE C.Client_ID IS NULL
AND C.User_ID IS NULL 

答案 1 :(得分:0)

尝试一下

SELECT DISTINCT X_ID, Y_ID, Client_Id, User_Id
FROM your_table