我試圖量化一些東西。這裏是(簡化當然)樣本:計算查詢中的百分比 - 訪問SQL
tblParent: { Number, Name }
tblChild: { Number, Name, ParentNumber, Criterion }
我想指望孩子具有相同ParentNumber
總數(方便使用GROUP BY和一個Count(1)),但問題比較該數字與ParentNumber
的的子女人數相同。
這是我到目前爲止有:
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;
所以我嘗試使用總數和找出有多少(作爲百分比)具有標準= 1。但是由於它使用的是子查詢,所以子查詢不能返回多個Total。我需要它返回每個ParentNumber的總數,用於具有該ParentNumber的每個Child的Percentage calc。
最終結果應該是:
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
...
這我喜歡..優雅和一個查詢。 Remou的答案也適用,但我認爲對於我的目的(如果有效),這樣做會更好。你會看到一個複選標記,如果這個工程。 – StuckAtWork
這似乎工作。對於Criterion = X,它很容易編輯,易於閱讀。謝謝! – StuckAtWork