In this example I am joining two tables.
DECLARE @AA TABLE
(
A1 INT,
A2 INT
)
DECLARE @BB TABLE
(
B1 INT,
B2 INT
)
INSERT INTO @AA values (1,1)
INSERT INTO @AA values (2,2)
INSERT INTO @AA values (3,3)
INSERT INTO @BB values (1,1)
INSERT INTO @BB values (2,2)
INSERT INTO @BB values (3,3)
SELECT A1, A2, B1, B2 from @AA a
JOIN @BB b on b.B1 = a.A1
where 1=1
and a.A1 in (1,2)
and b.B1 in (select max(bb.B1) from @BB bb JOIN @AA aa on bb.B1 = aa.A1 where aa.A1 in (1,2))
The above code is working since I am looking to get the result: “2,2,2,2”
Is there a more efficient way to do this? The inner select is pretty much the same as the outer select and to me it doesn’t look very nice.
You can just use
Rather than running the query once to get the
max(B1)then using the result of that in a filter against the same query.