At a guess, this should lower the query to a single scan/seek rather than 3. Tbhis does, however, assume that your lateral joins only return 1 row per value of SK
:
SELECT {Table A Columns},
oa.Sub1,
oa.Sub2,
oa.Sub3
FROM dbo.TableA A
OUTER APPLY (SELECT MAX(CASE B.rec WHEN '123' THEN COLX END) AS Sub1, --If rec is actually a numerical datatype, don't wrap it in single quotes (')
MAX(CASE B.rec WHEN '456' THEN COLX END) AS Sub2, --If rec is actually a numerical datatype, don't wrap it in single quotes (')
MAX(CASE B.rec WHEN '789' THEN COLX END) AS Sub3 --If rec is actually a numerical datatype, don't wrap it in single quotes (')
FROM dbo.TableB B
WHERE B.SK = A.SK) oa;
Of course, you'll still need the relevant indexes here; for TableB
, that would be on the column SK
and rec
and COLX
would want to at least be in the INCLUDE
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…