MS Access SubQueries

时间:2012-12-12 19:31:39

标签: sql ms-access subquery

我有一个简单的查询,它从一个Access表中选择数据。其中一个记录字段通过submittalID字段与另一个表中的四个日期(名为submittalfwd)相关联。我想为更大的查询返回的每条记录按升序(Date1,Date2,...)选择四个日期作为查询的一部分。

我知道LIMIT和OFFSET不能与Access一起使用,所以我不确定以升序顺序选择四条记录的最有效方式。

下面的查询几乎可以正常工作 - 但MS Access无法理解WHERE子句中的SUB.submittalID。

任何帮助将不胜感激。谢谢,

SELECT SUB.submittalID,

(SELECT TOP 1 subq2.subfwddate FROM
(SELECT TOP 2 subq2.subfwddate FROM submittalfwd AS subq2
WHERE subq2.submittal = SUB.submittalID ORDER BY subq2.subfwddate ASC)
ORDER BY subq2.subfwddate DESC) AS Date2

FROM submittals AS SUB;

示例数据 - submittalfwd表

subfwdID    submittal   subfwddate
1   1   12/9/2012
2   1   12/10/2012
3   1   12/11/2012
4   1   12/12/2012
5   2   12/13/2012
6   2   12/14/2012
7   2   12/15/2012
8   2   12/16/2012

2 个答案:

答案 0 :(得分:0)

MS Access无法理解Date2和Date3的WHERE子句中的SUB.submittalID(Date1和Date4正常工作),因为当你在date2和date3子查询中时,sub超出了范围。

尝试更多类似的内容:

SELECT 
sub.submittalID, specdivision, specsection, submittalnumber, 
miscnumber, submittaltitle, subcontractor, action, comments, 
open,

min_sfDate,

(select submittal, subfwddate_min2 from
   (SELECT TOP 1 submittal, subfwddate_min2 FROM 
      (SELECT TOP 2 submittal, subfwddate_min2 FROM submittalfwd ORDER BY subfwddate ASC) s2
   ORDER BY submittal, subfwddate_min2 DESC) AS min_sfDate_2nd
where sub.submittalid = submittal),

(select submittal, subfwddate_min3 from
   (SELECT TOP 1 submittal, subfwddate_min3 FROM 
      (SELECT TOP 3 submittal, subfwddate_min3 FROM submittalfwd ORDER BY subfwddate ASC) s3
   ORDER BY submittal, subfwddate_min3 DESC) AS min_sfDate_3rd,
where sub.submittalid = submittal),

max_sfDate

FROM submittals AS SUB inner join
(select submittal, min(subfwddate) as min_sfDate, max(subfwddate) as max_sfDate
from submittalfwd group by submittal) m on
sub.submittalID = m.submittal

或者,在我看来,更好的是为你的第二和第三分钟日期创建2个持久性查询,并将它们加入到这个主要日期。更容易理解和调试。

答案 1 :(得分:0)

我担心这不是你想要的,但为什么你不能只做相对简单的事情:

SELECT s.SubmittalID [Submittal], sf.SubFwdDate [Forward Date]
FROM submittals s LEFT JOIN submittalfwd sf ON s.SubmittalID = sf.SubmittalID
ORDER BY 1, 2