我正在尝试运行查询,以查找每个客户和部分的最新PRICE。我的参数是This_Customer,This_Part和This_Date。任何留空null的参数都应该返回该字段的所有值。
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
通过运行以下两个查询,我已经能够为每个客户,部分和日期找到合适的记录,但只有在我排除价格时它才会工作。
第一个查询使用带有< = 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
答案 0 :(得分:0)
我会使用一个“指针”查询来获取每个Customer和Part的最新日期(在这种情况下,我只是通过使用Date()函数来使用今天的日期,但是你可以将它变成一个变量):
SELECT Table1.Customer, Table1.Part, Max(Table1.BegDate) AS MaxOfBegDate
FROM Table1
GROUP BY Table1.Customer, Table1.Part
HAVING (((Max(Table1.BegDate))<=Date()));
您可能需要更改HAVING子句以包含Part和Customer。
然后将指针连接到原始表格,以便为正确的日期输入ID和价格:
SELECT Table1.ID, Table1.Customer, Table1.Part, Table1.BegDate, Table1.Price
FROM Query1 INNER JOIN Table1 ON (Query1.MaxOfBegDate = Table1.BegDate) AND (Query1.Part = Table1.Part) AND (Query1.Customer = Table1.Customer);