我正在尝试在SQL Server 2005中执行过滤操作。
实施例。假设我们有两个表,Current和Reject。
Current = 1, 2, 3, 4, 5, 1, 2
Reject = 2, 3, 4
Current \ Reject = 1, 2, 5
如您所见,这两个表共享值。我基本上只想减去这些共享值并将它们放入一个新表中。
这是我尝试过的,但它不起作用。 (A是要匹配的列)。
select * from Current left join
Reject on csrp.a = rp.a
group by Current.a, Reject.a
having count(Current.a) > count(Reject.a)
请注意,元素2已被过滤掉,即使它不应该被过滤掉。
Martin Smith的回答适用于此案例!
修改
好的,让我们复杂一点吧。假设我有与以前完全相同的情况,除非这次我需要匹配三列而不是一列?
Current = (1, 2, 3), (2, 3, 4), (2, 3, 4), (4, 5, 6), (7, 8, 9), (1, 2, 3)
Reject = (2, 3, 4), (4, 5, 6), (7, 8, 9)
Current \ Reject = (1, 2, 3), (2, 3, 4)
答案 0 :(得分:1)
WITH [Current](a, b, c)
AS (SELECT 1, 2, 3 UNION ALL
SELECT 2, 3, 4 UNION ALL
SELECT 2, 3, 4 UNION ALL
SELECT 4, 5, 6 UNION ALL
SELECT 7, 8, 9 UNION ALL
SELECT 1, 2, 3),
Reject(a, b, c)
AS (SELECT 2, 3, 4 UNION ALL
SELECT 4, 5, 6 UNION ALL
SELECT 7, 8, 9 ),
T(RN, a, b, c)
AS (SELECT ROW_NUMBER() OVER (PARTITION BY a, b, c ORDER BY (SELECT 0)),
a,
b,
c
FROM [Current]
EXCEPT
SELECT ROW_NUMBER() OVER (PARTITION BY a, b, c ORDER BY (SELECT 0)),
a,
b,
c
FROM Reject)
SELECT DISTINCT a,
b,
c
FROM T