Access 2003:如何组合两个计数查询

时间:2010-09-27 22:01:01

标签: sql ms-access

我正在编写我的第一个小型Access 2003应用程序。我有两个问题,我无法弄清楚如何结合。我想要的是获取日期范围内的所有路线编号,计算日期范围内每条路线的总行数,并计算延迟的数量。我有这两个查询让我在那里的一部分,只是无法弄清楚如何在Access查询中组合它们。

PARAMETERS StartDate DateTime, EndDate DateTime;
SELECT [ROUTE #], Count(*) AS Total
FROM [On time performace audits] 
WHERE ((([On time performace audits].DATE) Between [StartDate] And [EndDate]))
GROUP BY [Route #];

PARAMETERS StartDate DateTime, EndDate DateTime;
SELECT [Route #], Count(*) as Late
FROM [On time performace audits]
WHERE ([On time performace audits].DATE Between [StartDate] And [EndDate]) AND (    Minute( [ACTUAL TIME]- [SCHEDULED TIME]) >=6)
GROUP BY [Route #];

我不是一个SQL人,更像是一个LINQ人,在习惯VS2010后在Access 2003中编写一个快速而又脏的应用程序有点痛苦。无论如何,希望你能帮忙。 感谢。

3 个答案:

答案 0 :(得分:0)

在第二个示例查询中,您确定要使用Minute()函数吗?

如果您希望持续2个日期/时间值,请使用DateDiff()函数。

Debug.Print DateDiff("n", #2010/09/27 01:00#, #2010/09/27 02:10#)
70

Debug.Print Minute(#2010/09/27 02:10# - #2010/09/27 01:00#)
10

如果你想要DateDiff()方法,试试这个:

PARAMETERS StartDate DateTime, EndDate DateTime;
SELECT t.[ROUTE #], t.Total, l.Late
FROM
    (SELECT [ROUTE #], Count(*) AS Total
    FROM [On time performace audits]
    WHERE ((([DATE]) Between [StartDate] And [EndDate]))
    GROUP BY [ROUTE #]) AS t
    LEFT JOIN (
        SELECT [ROUTE #], Count(*) AS Late
        FROM [On time performace audits]
        WHERE ((([DATE]) Between [StartDate] And [EndDate]))
            And DateDiff("n",[SCHEDULED TIME],[ACTUAL TIME]) >= 6
        GROUP BY [ROUTE #]
        ) AS l
    ON t.[ROUTE #] = l.[ROUTE #];

注意我在DATE字段名称后面加上方括号,以区别于VBA Date()函数。

答案 1 :(得分:0)

您还可以使用UNION [ALL]查询将结果集合并为一个...

答案 2 :(得分:0)

问题是如何组合这两个查询。 UNION ALL将是IMO的最佳方式,如下所示:

PARAMETERS StartDate DateTime, EndDate DateTime;
SELECT 'All' As Type, [ROUTE #], Count(*) AS Total
FROM [On time performace audits]  
WHERE DATE Between StartDate And EndDate
GROUP BY [Route #]
UNION ALL
SELECT 'Late', [Route #], Count(*)
FROM [On time performace audits] 
WHERE DATE Between StartDate And [EndDate AND 
(Minute( [ACTUAL TIME]- [SCHEDULED TIME]) >=6) 
GROUP BY [Route #];