我目前正在为Access 97进行SQL查询。给出了以下表(为演示目的进行了简化),每个表都位于单独的mdb文件中:
Table1 in C:dbdb1.mdb:
PartyId (PK) Name
------------ --------
1 A
2 B
3 C
C:dbdb2.mdb:
PartyId (PK) Date (PK) Value
------------ --------- -----
1 6/30/2014 4
1 7/1/2014 8
2 5/3/2014 3
3 5/5/2014 5
3 5/3/2014 1
3 5/2/2014 2
在这里,我想根据定义的日期查找各方的最新值。因此,假设我将7/5/2014标记为目标日期,那么我的查询应该返回以下内容:
PartyId Name Date Value
------- ---- -------- -----
1 A 7/1/2014 8
2 B 5/3/2014 3
3 C 5/5/2014 5
我在C:dbdb1中创建了以下查询。mdb数据库:
SELECT T.TPartyId, Name, T.TDate, T.TValue
FROM Table1 INNER JOIN [
SELECT Table2.PartyId AS TPartyId, MAX(Table2.Date) AS TDate, FIRST(Value) AS TValue
FROM Table2 IN 'C:dbdb2.mdb'
WHERE Table2.Date <= #7/5/2014#
GROUP BY Table2.PartyId]. AS T
ON (Table1.PartyId = T.TPartyId);
问题是Table2实际上位于一个密码保护的数据库文件中。因此,我尝试修改查询,如http://support.microsoft.com/kb/113701中所述,如下所示:
SELECT T.TPartyId, Name, T.TDate, T.TValue
FROM Table1 INNER JOIN [
SELECT Table2.PartyId AS TPartyId, MAX(Table2.Date) AS TDate, FIRST(Value) AS TValue
FROM [;database=C:dbdb2.mdb;PWD=mypwd].Table2
WHERE Table2.Date <= #7/5/2014#
GROUP BY Table2.PartyId]. AS T
ON (Table1.PartyId = T.TPartyId);
但是,这总是导致语法错误。我怀疑
中的后续括号INNER JOIN [ … [;database= … ] … ]
语句是失败的原因。不幸的是,Access 97总是要求别名用方括号括起来,后面跟着一个句号,而Access 2000及更高版本没有这个限制。有什么方法可以用Access 97来完成这个查询吗?谢谢。
最后,经过无数次的尝试&错误会话,我找到了一个解决方案。这行代码似乎可以工作,并且还避免了在彼此后面放置两个开始方括号:
FROM Table2 IN '' ';database=C:dbdb2.mdb;PWD=mypwd'
Create Qry1 ="SELECT Table2.PartyId AS TPartyId,
MAX(Table2.Date) AS TDate, FIRST(Value) AS TValue
FROM [;database=C:dbdb2.mdb;PWD=mypwd].Table2
WHERE Table2.Date <= #7/5/2014#
GROUP BY Table2.PartyId "
SELECT T.TPartyId, Name, T.TDate, T.TValue
FROM Table1 INNER JOIN Qry1
ON (Table1.PartyId = Qry1.TPartyId);