Это выглядит нормально, я думаю, что это можно улучшить, хотя.
DECLARE @DataIn TABLE
(
QID INT NOT NULL,
RID INT NOT NULL,
DOB DATE NOT NULL
)
INSERT INTO @DataIn
VALUES
(1,1,'01/01/1980'),
(1,2,'03/01/1981'),
(1,3,'01/02/1991')
DECLARE @WDATA TABLE
(
QID INT NOT NULL,
RID INT NOT NULL,
PID INT NOT NULL
)
INSERT INTO @WDATA
VALUES
(1,1,101),
(1,1,102),
(1,3,204)
;WITH OuterCTE(QID, RID, PID) AS
(
SELECT
ISNULL(D.QID, W.QID) AS QID,
ISNULL(D.RID, W.RID) AS RID,
W.PID
FROM @DataIn AS D FULL OUTER JOIN @WDATA AS W ON W.RID = D.RID AND W.QID = D.QID
)
SELECT
CTE.QID,
CTE.RID,
CTE.PID,
CASE
WHEN COUNT(W.PID) = 0 THEN 'no match'
WHEN COUNT(W.PID) = 1 THEN 'single match'
ELSE 'multiple match'
END
FROM
OuterCTE AS CTE
LEFT JOIN @WDATA AS W
ON CTE.QID = W.QID
AND CTE.RID = W.RID
GROUP BY
CTE.QID,
CTE.RID,
CTE.PID