SET STATISTICS IO ON;
SET NOCOUNT ON;
DECLARE @Old TABLE (
Id INT PRIMARY KEY,
Col1 INT NULL,
Col2 VARCHAR(50) NULL
);
DECLARE @New TABLE (
Id INT PRIMARY KEY,
Col1 INT NULL,
Col2 VARCHAR(50) NULL
);
INSERT @Old (Id, Col1, Col2)
SELECT 1, 11, 'A'
UNION ALL SELECT 2, 22, 'B'
UNION ALL SELECT 3, 33, 'C'
UNION ALL SELECT 4, NULL, NULL
UNION ALL SELECT 5, NULL, NULL;
INSERT @New (Id, Col1, Col2)
SELECT 1, 11, 'A'
UNION ALL SELECT 2, 222, 'B'
UNION ALL SELECT 3, NULL, 'C'
UNION ALL SELECT 4, 44, NULL
UNION ALL SELECT 5, NULL, NULL;
PRINT 'Begin of test';
PRINT '@Old:';
SELECT * FROM @Old;
PRINT '@New:';
SELECT * FROM @New;
PRINT 'Last SELECT:'
SELECT *
FROM (
SELECT x.Id, x.Col1, x.Col2, x.Rowtype,
DENSE_RANK() OVER(PARTITION BY x.Id ORDER BY x.Col1, x.Col2) AS Rnk1,
DENSE_RANK() OVER(PARTITION BY x.Id ORDER BY x.Col1 DESC, x.Col2 DESC) AS Rnk2
FROM (
SELECT o.Id, o.Col1, o.Col2, 1 AS RowType
FROM @Old o
UNION ALL
SELECT n.Id, n.Col1, n.Col2, 2 AS RowType
FROM @New n
) x
) y
--WHERE y.RowType=1 AND (y.Rnk1=2 OR y.Rnk2=2) -- Only old rows
WHERE y.RowType=2 AND (y.Rnk1=2 OR y.Rnk2=2) -- Only new rows
PRINT 'End of test';
结果:
Id Col1 Col2 Rowtype Rnk1 Rnk2
-- ---- ---- ------- ---- ----
2 222 B 2 2 1
3 NULL C 2 1 2
4 44 NULL 2 2 1
留言:
Begin of test
@Old:
Table '#671F4F74'. Scan count 1, logical reads 2
@New:
Table '#6AEFE058'. Scan count 1, logical reads 2
Last SELECT:
Table '#6AEFE058'. Scan count 1, logical reads 2
Table '#671F4F74'. Scan count 1, logical reads 2
End of test