1

我试图量化一些事情。这是一个示例(当然是简化的):

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

我想计算具有相同的孩子的总数(很容易使用 Group By 和 Count(1) ),但问题是将该数字与具有相同的孩子ParentNumber的数量进行比较。ParentNumberCriterion = "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 的孩子的百分比计算。

最终结果应该是:

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

我有几个这样的查询,我将它们合并到一个报告中以生成一个完整的报告,按父母分组,显示所有父母的所有“标准=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...

4

2 回答 2

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 = 10ParentNumberCount(*)


更新

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

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为零。

于 2012-07-04T13:42:11.443 回答
1

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

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

您还可以创建计数查询

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

然后将这两个查询添加到设计网格中,将它们连接到父节点上。

于 2012-07-04T13:25:12.117 回答