我正在尝试运行查询,以找到每个客户和零件的最新价格。我的参数是 This_Customer、This_Part 和 This_Date。任何留空的参数都应返回该字段的所有值。
表格1
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
通过运行以下两个查询,我已经能够为每个客户、零件和日期找到合适的记录,但它只有在我排除价格时才有效。
第一个查询使用具有 <=0 条件的 DateDiff 函数来查找小于 This_Date 的所有日期。
查询 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,"*")));
第二个查询使用 Max 函数从 This_Date 中查找天数最少的记录(负 DaysSince 值最接近或等于零)。
查询 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;
如何在不影响 NearestDateQuery 结果的情况下将 Table1.Price 值添加到 NearestDateQuery?似乎应该有一个简单的解决方案,但我就是不明白。
为进一步清楚起见,以下是该查询应如何工作的大量示例。
感谢您的任何帮助!
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