OP’s original question title: Use a field from one query in a subquery
I am not all that experienced in writing queries in Access and I’m having some trouble.
I have a few tables. 1 for Products, 1 for Markets and 1 for Facts which combine the Markets and Products. I need to write a query that can join those together and for every instance of a specific market field (MF), I need to return the nth highest of a specific fact field (FF) (summed up per market/product) and which of a specific product field (PF) that fact value it is links to. Hope that makes sense.
Anyway, here is the query I have:
select market.MF2, product.PF10, sum(fact.FF3) as FF3
from mMarket market, mProduct product, mFact fact
where market.Item_ID = fact.Market_ID
and product.Item_ID = fact.Product_ID
and FF3 =
(
select min(FF3) from
(
select TOP 2 FF3 from
(
select market2.MF2, product2.PF10, sum(fact2.FF3) as FF3
from mMarket market2, mProduct product2, mFact fact2
where market2.Item_ID = fact2.Market_ID
and product2.Item_ID = fact2.Product_ID
and market2.MF2 = market.MF2
group by market2.MF2, product2.PF10
order by 3 DESC
)
)
)
group by market.MF2, product.PF10
The TOP 2 part is where to specify n easily.
The problem I am having is that when I run this in access, It prompts me to enter a value for market.MF2 (I presume this is referring to the instance of it in the subquery).
I was thinking that the code would grab that value from main query for each row but clearly its not doing that.
Tables below:
mMarket
Item_ID MF2
---------------
1 64
2 28
3 73
mProduct
Item_ID PF5 PF10
----------------------------
1 2221 Category1
2 6487 Category3
3 73234 Category2
4 76223 Category1
5 99342 Category2
mFact
Market_ID Product_ID FF3
--------------------------------------
1 1 1000
1 2 1500
1 3 500
1 4 1000
2 1 1500
2 3 1000
2 5 1500
3 1 1000
3 2 500
3 5 2000
What is wrong with the query? I can’t see it
Thank in advance
Expected Results:
If n was 1
MF2 PF10 FF3
----------------------------
64 Category1 2000
28 Category2 2500
73 Category2 2000
If n was 2
MF2 PF10 FF3
----------------------------
64 Category3 1500
28 Category1 1500
73 Category1 1000
Take a look at this reference please:
Query Sum just by Market:
Results Sum just by Market:
Query Sum by Market, Category :
Results Sum by Market, Category :
UPDATED ANSWER as per OP’s later comments
Query:
Results:
Based on OP’s expected results – updated to comply with MS ACCESS SQL
There are many ways to achieve this in MYSQL. However wanted to give OP the answer for MS ACCESS.
I suggest you save the above Results from ** Sum by Market, Category** query into a temp table or to a MS ACCESS Query. Then use that Query in your final Query.
Query for Top 1st by Market by Category:
Results for Top 1st Market by Category:
Results for Top 2nd Market by Category:
Results for Top 3rd Market by Category: