0

我正在尝试编写一个简单的聚合查询,但遇到了一些问题。

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

到目前为止,我有前两行

     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

或者

 Status    Countnums      
 __________         
 Complete  100            
 Incomplete 100           
 percentComplete     50

虽然,我看不到后者将如何在行级别上工作。这是在 MS Access 中。

4

3 回答 3

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是一个保留字。将其用作别名而不用方括号括起来会引发错误。

于 2012-12-08T22:26:23.863 回答
1

在 SQL 服务器中

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

在访问

SELECT tblStuff.Status, Count(*) AS cnt, (SELECT COUNT(*) FROM tblStuff as t1) AS fcnt, [cnt]/[fcnt] AS perc
FROM [tblStuff]
GROUP BY tblStuff.Status
于 2012-12-08T21:27:19.457 回答
1

这将很好地完成这项工作。

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

你可以得到相关的总数,但这在性能上确实没有什么不同,并且可能更清晰。

于 2012-12-08T21:27:28.970 回答