Can this MS-Access query be improved?
i.e. the “SELECT TOP 1 col FROM Table2” line is repeated
If there is an index before curindex in Table2,
the query returns the previous value of col from Table2,
otherwise the value of col matching id is returned from Table3.
i.e.
if curindex = 7 value returned = 221 from Table2
if curindex = 5 value returned = 200 from Table3
Table2 Table3
id index col id col
1 1 110 1 100
1 2 120 2 200
1 3 130 3 300
1 4 140
2 5 211
2 6 221
2 7 231
PARAMETERS [curindex] Short;
SELECT TOP 1
IIF (
( SELECT TOP 1 col
FROM Table2
WHERE index < [curindex]
AND id =
( SELECT id
FROM Table2
WHERE index = [curindex])
) ,
( SELECT TOP 1 col
FROM Table2
WHERE index < [curindex]
AND id =
( SELECT id
FROM Table2
WHERE index = [curindex])
ORDER BY index DESC
),
( SELECT TOP 1 col
FROM Table3
WHERE id =
( SELECT id
FROM Table2
WHERE index = [curindex])
)
) AS col
FROM Table2
ORDER BY index
You can limit the cost of the iff condition by reducing your result query.
ie