Hi,
You can add a GROUP BY (the primary key of the first table) and a COUNT(*)
to know if just one match, or more, are possible.
SELECT a.pk, MAX(b.pk), COUNT(*)
FROM ...
GROUP BY a.pk
IF more than one match is possible, for many original records, you need an
assignation algorithm and in general, I would not use SQL to write it. The
possible algorithm are the Simplex method, or, in this case, the graph
theory about finding the maximum flow.
Graph Theory based method: Basically, at the left, draw a single node, the
source, S. Then, to its right, in a single column, draws all the records (as
node for the graph), on a common vertical. Let us call these nodes the A
nodes. Link the Source, S, to each A node, with a link of capacity of 1.
Next, a little bit to the right, draw the records, again, in another column,
that will be the B nodes (in the same order, downward, that for the A
nodes). Link each A node to each B node but only if the difference in price
is less than 5. Do not link two nodes one the same line, though. Do not link
a A node to a B node if the B node is upper up than the A node. Again, each
link has a capacity of 1. Finally, to complete the graph, add a single sink
node, T (terminal) and link each B node to T, each link with a capacity of
1. Now, starts the pump, and, from S, pump as much water as you can, but
note that the pipes have a finite capacity. Once you have your maximum flow
from S to T, if you look at the pipes with water in them between A nodes and
B nodes, those pipes filled with water ARE your assignations. Indeed, each
node A would get just ONE pipe, between A and B, filled with water, because
although if many pipes get out of some A-node, only one pipe get into it,
from the source, and, sure, the amount of water is "preserved" (amount out
= amount in), which is automatically taken into account by the Max Flow
Algorithm. Also, since all coefficients are 1, no fractional answer would
naturally occur. So, we have the graph, just left to you to apply the Max
Flow Algorithm, or the Simplex method, if you prefer (more general, and
probably faster too, at least, than Ford-Fulkerson). But that is not job
done with SQL, in general.
Hoping it may help,
Vanderghast, Access MVP