我试图量化一些事情。这是一个示例(当然是简化的):
tblParent: { Number, Name }
tblChild: { Number, Name, ParentNumber, Criterion }
我想计算具有相同的孩子的总数(很容易使用 Group By 和 Count(1) ),但问题是将该数字与具有相同的孩子ParentNumber
的数量进行比较。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 的孩子的百分比计算。
最终结果应该是:
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
...