There are 2 very different ways to do it:
1. You can do all the queries in advance and build the result in the page before it was loaded
2. Each click can call PHP, put data in layer and display it
Solution 1 sounds quite easy. You do you Query B for each row and put output in <div id="res_n" class=res></div>. In the head, use CSS to hide div.res by default. In each link created by Query A put onClick="showHideLayer('res_n'; return false". showHideLayer is the function that will change visibility of the layer. You need to build it differently for NS and IE.
I don't like this solution because the resulting page will be big and it may be bad for bandwidth. Also, can be hard on server if number of results of Query A is big.
Solution 2 is kinda hard from at point of JavaScript. You need to load external file (result of your click which would call Query B with parameter n) to layer. I do have this code somewhere, but don't know where. If this is what you need, let me know and I'll look for it.
This solution is kind of slow because user has to wait after each click. Still, this might be a good solution for Intranet where speed is no problem.
You might want to try hybrid solution, but this is much more complicated. First you list all the links, with onClick="clicked(n); return false;". Then list DIVs. JavaScript function clicked() than needs to check if the div called res_n (as show above) exists. If so, display it as in solution 1. If not, use solution 2.