结合两个SQL SELECT COUNT(*)语句

时间:2013-06-05 09:28:17

标签: sql ms-access ms-access-2007 access-vba

我正在使用Microsoft Access 2007.我有两个SELECT COUNT(*)语句在没有组合的情况下运行正常,但我希望将这些语句组合起来用作通过VBA的表单记录源。

1. SELECT Count(*) AS OrderCount FROM (SELECT DISTINCT OrderNo FROM tblDisposition);"

2. SELECT Count(*) AS ReviewCount FROM tblDisposition WHERE [ReviewClose]=0;

我知道已经有很多这样的问题,例如:

two SQL COUNT() queries?

Access 2007: "SELECT COUNT(DISCTINCT ..."

How do I combine 2 select statements into one?

还有更多。这是我尝试但仍然失败的原因:

SELECT (SELECT Count(*) AS OrderCount FROM (SELECT DISTINCT OrderNo FROM tblDisposition)),"
        (SELECT Count(*) AS ReviewCount FROM tblDisposition WHERE [ReviewClose]=0);"

我将myForm上的组合SQL语句设置为recordsource,我有两个文本字段,我将controlsource设置为OrderCount和ReviewCount。在我设置recorsource的表单加载事件中,两个文本字段都给出了#NAME错误,但如果我只设置了一个SQL语句,它将在文本字段中显示正确的计数。

2 个答案:

答案 0 :(得分:3)

您可以使用以下SQL语句将两个计数作为两个值放在一行中:

SELECT 
    (
        SELECT Count(*) AS OrderCount 
        FROM 
            (
                SELECT DISTINCT OrderNo FROM tblDisposition
            )
    ) AS OrderCount,
    (
        SELECT Count(*) AS ReviewCount 
        FROM tblDisposition 
        WHERE [ReviewClose]=0
    ) AS ReviewCount
FROM
    (
        SELECT COUNT(*) FROM tblDisposition
    )

请注意,最后的FROM子句实际上只是让查询返回单行的一种方法。这也可以通过Dual表来完成,描述为here

答案 1 :(得分:1)

我认为你的查询根本不起作用。尝试像这样添加'* FROM':

SELECT * FROM 
(SELECT Count(*) AS OrderCount FROM (SELECT DISTINCT OrderNo FROM tblDisposition)),
(SELECT Count(*) AS ReviewCount FROM tblDisposition WHERE [ReviewClose]=0)