计算查询中的百分比 - 访问SQL

时间:2012-07-04 13:20:29

标签: sql ms-access group-by percentage

我正在尝试量化一些事情。这是一个样本(当然简化):

tblParent: { Number, Name }
tblChild: { Number, Name, ParentNumber, Criterion }

我想计算具有相同ParentNumber的儿童总数(使用分组依据和计数(1)容易),但问题是将该数字与具有分组数量的儿童数量进行比较拥有ParentNumber的同一Criterion = "Something"

这是我到目前为止所拥有的:

SELECT "Criterion = 1" AS CritDesc,
COUNT(1) AS Total,
ParentNumber AS Parent,
( COUNT(1) / (SELECT Total FROM [TotalCountingQuery]) ) AS Percentage
FROM tblChild
WHERE Criterion = 1
GROUP BY ParentNumber;

[TotalCountingQuery]只计算每个ParentNumber的所有子项,并将该总数计入Total

SELECT COUNT(1) AS Total FROM tblChild GROUP BY ParentNumber;

所以我试图使用那个TOTAL计数并计算出Criterion = 1的数量(百分比)。但由于它使用的是子查询,因此子查询不能返回多个Total。我需要它来返回每个ParentNumber的总数,以便在具有该ParentNumber的每个Child的百分比计算中使用。

最终结果应为:

CritDesc   |    Total    |   Parent    |   Percentage
```````````````````````````````````````````````````````
Criterion=1|      2      |   45011     |      0.333    // Means there should be 6 Children with 45011 as parent
Criterion=1|      4      |   43255     |       0.9
Criterion=1|      1      |   59056     |      0.44

我有几个这样的查询,我在报告中生成一个完整的报告,按父级分组,显示所有父母的所有“Criterion = X”。那是有效的,我只需要上面的工作。

想法?

编辑:我为此目的尝试加入:

SELECT "Criterion=1" AS CritDesc,
COUNT(c.Number) AS Total,
ParentNumber AS Parent,
COUNT(c.Number)/q.Total AS Percentage
FROM tblChild AS c INNER JOIN tblParent AS q ON c.ParentNumber = q.Number
GROUP BY ParentNumber

抛出:You tried to execute a query ... 'Count(1)/q.Total' as part of an aggregate function。将其添加到group-by语句会抛出Cannot have aggregate function in GROUP BY ...

2 个答案:

答案 0 :(得分:5)

您的子查询没有where子句,因此会对所有记录进行计数,但您可以在没有子查询的情况下执行此操作

SELECT
    "Criterion = 1" AS CritDesc,
    SUM(IIf(Criterion = 1, 1, 0)) AS NumCrit,
    COUNT(*) AS TotalNum,
    SUM(IIf(Criterion = 1, 1, 0)) / COUNT(*) AS Percentage,
    ParentNumber AS Parent
FROM
    tblChild
GROUP BY
    ParentNumber;

注意:我删除了WHERE子句。相反,我通过总结1 Criterion = 10来计算符合标准的记录。这样我就可以使用ParentNumber同时获得每Count(*)的总数。


更新

您可能希望获得没有孩子的父母的结果。在这种情况下,您可以使用外部联接

SELECT
    "Criterion = 1" AS CritDesc,
    SUM(IIf(C.Criterion = 1, 1, 0)) AS NumCrit,
    COUNT(C.Number) AS TotalNumOfChildren,
    SUM(IIf(C.Criterion = 1, 1, 0)) / COUNT(*) AS Percentage,
    P.Number AS Parent
FROM
    tblChild AS C
    LEFT JOIN tblParent AS P
        ON C.ParentNumber = P.Number  
GROUP BY
    P.Number;

请注意,我得到Count(C.Number)的孩子总数,因为Count(*)会计算没有孩子的记录,在这种情况下会产生1。但是,在百分比计算中,我除以Count(*)以避免除以零。在这种情况下,结果仍然是正确的,因为Criterion = 1的记录总和将为零。

答案 1 :(得分:1)

如果您在MS Access中工作,则可以除以父母的DCount。

Total/DCount("Parent","Table","Parent=" & Parent)

您还可以创建计数查询

SELECT Parent, Count(Parent) FROM Table GROUP BY Parent

然后将两个查询添加到设计网格中,将它们连接到Parent。