My table structures are shown here:
Table1
| Col1 |
|---|
| 20 |
| 20 |
| 20 |
| 40 |
| 50 |
| 60 |
Table2
| Col1 |
|---|
| 20 |
| 30 |
| 40 |
| 60 |
My expected result is this:
| Col1 | Col2 |
|---|---|
| 20 | Matched |
| 20 | Not Matched |
| 20 | Not Matched |
| 30 | Not Matched |
| 40 | Matched |
| 50 | Not Matched |
| 60 | Matched |
Query I'm trying to use:
WITH cte1 AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col1) rn
FROM Table1
),
cte2 AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col1) rn
FROM Table2
)
SELECT T1.Col1,
CASE WHEN T2.Col1 IS NOT NULL THEN 'Matched' ELSE 'NotMatched' END AS Col2
FROM cte1 T1
LEFT JOIN cte2 T2
ON T1.Col1 = T2.Col1 AND T1.rn = T2.rn
ORDER BY T1.Col1, T2.Col1 DESC;
You are halfway there. To identify matches and mismatches from either side of the join, you need to perform a
FULL OUTER JOINand the check for bothT1.Col1 IS NOT NULL AND T2.Col1 IS NOT NULLin yourCASEexpression. To includeCol1in your results for all cases, you can useISNULL(T1.Col1, T2.Col1) AS Col1.Results:
See this db<>fiddle.