从聚合查询计算的行

时间:2012-12-08 21:25:18

标签: sql ms-access

我正在尝试编写一个简单的聚合查询,但正在努力解决问题。

我有一个状态字段为“完成”或“未完成”的表格。 我希望查询返回三行:完成的数量,不完整的数量和计算的完成百分比。

到目前为止,我的前两行是

     SELECT Status, Count(*) as countNums FROM tblStuff GROUP BY Status

所以这会返回类似

的内容
 Status    Countnums
 __________         
 Complete  100
 Incomplete 100

我想要的是

 Status    Countnums      Percent
 __________         
 Complete  100             50
 Incomplete 100            50

OR

 Status    Countnums      
 __________         
 Complete  100            
 Incomplete 100           
 percentComplete     50

虽然,我不知道后者如何在行级工作。 这是在MS Access中。

3 个答案:

答案 0 :(得分:2)

您可以将现有的GROUP BY查询用作子查询,并将其与另一个子查询交叉连接,该子查询返回tblStuff的总计数。使用子查询值在父查询中派生[Percent]

这对Access 2007有效(正确的结果;没有语法错误):

SELECT
    group_counts.Status,
    group_counts.countNums,
    (group_counts.countNums / total_count.total_nums * 100) AS [Percent]
FROM
    (
        SELECT Status, Count(*) AS countNums
        FROM tblStuff GROUP BY Status
    ) AS group_counts,
    (
        SELECT Count(*) AS total_nums
        FROM tblStuff
    ) AS total_count;

请注意Percent是保留字。使用它作为别名而不用方括号括起来会引起错误。

答案 1 :(得分:1)

在SQL SERVER中

SELECT Status, Count(*) AS cnt, CAST( Count(*) as decimal) / (SELECT COUNT(*) FROM tblStuff) AS perc 
FROM tblStuff 
GROUP BY Status

您甚至可以将完整计数保存在变量

DECLARE @fcnt decimal

SELECT @fcnt = COUNT(*) FROM tblStuff
SELECT Status, Count(*) AS cnt,Count(*) / @fcnt AS perc 
    FROM tblStuff 
    GROUP BY Status

在Access中

SELECT tblStuff.Status, Count(*) AS cnt, (SELECT COUNT(*) FROM tblStuff as t1) AS fcnt, [cnt]/[fcnt] AS perc
FROM [tblStuff]
GROUP BY tblStuff.Status

答案 2 :(得分:1)

这样就可以了。

SELECT
   Status,
   Count(*) AS CountNums,
   Count(*) / DCount("*", "tblStuff") AS Pct
FROM
   tblStuff
GROUP BY Status

您可以获得相关的总计数,但这在性能方面确实没有什么不同,并且可能更清晰。