I am trying to run a query to that will find the most recent PRICE per customer and part. My parameters are This_Customer, This_Part, and This_Date. Any parameter left null should return all values for that field.
TABLE1
ID | Customer | Part | BegDate | Price
101 1 A 1/1/2013 $1
102 2 A 2/1/2013 $2
103 2 A 3/1/2013 $3
104 1 B 4/1/2013 $4
105 2 B 5/1/2013 $5
By running the two following queries, I have been able to accomplish finding the appropriate RECORDS per customer, part, and date, but IT WILL ONLY WORK IF I EXCLUDE PRICE.
The first query uses the DateDiff function with <=0 criteria to find all dates less than This_Date.
Query 1 “DaysSinceQuery”:
SELECT DateDiff("d",This_Date,BegDate) AS DaysSince, Table1.Part, Table1.Customer, Table1.BegDate, Table1.Price, Table1.ID
FROM Table1
WHERE (((DateDiff("d",This_Date,BegDate))<=0) AND ((Table1.Part) Like IIf(This_Part<>"",This_Part,"*")) AND ((Table1.Customer) Like IIf(This_Customer<>"",This_Customer,"*")));
The second query uses the Max function to find the record with the fewest number of days from This_Date (negative DaysSince value closest or equal to zero).
Query 2 “NearestDateQuery”:
SELECT Max(DaysSinceQuery.DaysSince) AS NearestDate, Table1.Part, Table1.Customer
FROM Table1 INNER JOIN DaysSinceQuery ON Table1.ID = DaysSinceQuery.ID
GROUP BY Table1.Part, Table1.Customer;
How do I add the Table1.Price values to NearestDateQuery without affecting the NearestDateQuery results? It seems like there should be a simple solution, but I just can’t get it.
For further clarity, below are numerous examples of how this query should work.
Thank you for any help!
QUERY EXAMPLE 1
This_Customer 2
This_Part A
This_Date 2/15/2013
ID | Customer | Part | BegDate | Price
102 2 A 2/1/2013 $2
QUERY EXAMPLE 2
This_Customer NULL
This_Part A
This_Date 2/15/2013
ID | Customer | Part | BegDate | Price
102 2 A 2/1/2013 $2
QUERY EXAMPLE 3
This_Customer 2
This_Part NULL
This_Date 5/15/2013
ID | Customer | Part | BegDate | Price
103 2 A 3/1/2013 $3
105 2 B 5/1/2013 $5
QUERY EXAMPLE 4
This_Customer 2
This_Part A
This_Date NULL
ID | Customer | Part | BegDate | Price
102 2 A 2/1/2013 $2
103 2 A 3/1/2013 $3
QUERY EXAMPLE 5
This_Customer NULL
This_Part A
This_Date NULL
ID | Customer | Part | BegDate | Price
101 1 A 1/1/2013 $1
102 2 A 2/1/2013 $2
103 2 A 3/1/2013 $3
QUERY EXAMPLE 6
This_Customer NULL
This_Part NULL
This_Date 4/15/2013
ID | Customer | Part | BegDate | Price
103 2 A 3/1/2013 $3
104 1 B 4/1/2013 $4
QUERY EXAMPLE 7
This_Customer 2
This_Part NULL
This_Date NULL
ID | Customer | Part | BegDate | Price
102 2 A 2/1/2013 $2
103 2 A 3/1/2013 $3
105 2 B 5/1/2013 $5