2013-10-11 136 views
3

如何獲得計數百分比?在嘗試根據行數計算百分比時,我得到的值都是相同的。我想每個屬性的百分比取決於COUNT的數量。因此,如果我計算30次屬性,我希望將其更改爲百分比,具體取決於行數和其他值。計數百分比SQL

SELECT Attribute 
     , COUNT(Attribute)/COUNT(*) * 100 AS TopIssues 
FROM Audits 
     WHERE MONTH(TransActionDate) = MONTH(GETDATE()) 
GROUP BY Attribute 
ORDER BY COUNT(Attribute) DESC  

回答

3

在SQL Server,你可以使用:

SELECT Attribute 
     , COUNT(Attribute)*1.0/SUM(COUNT(*)) OVER() * 100 AS TopIssues 
FROM Audits 
WHERE MONTH(TransActionDate) = MONTH(GETDATE()) 
GROUP BY Attribute 
ORDER BY COUNT(Attribute) DESC 
0

你也可以做這樣的事情:

SELECT Attribute 
     , COUNT(Attribute)*1.0/ACount AS TopIssues 
FROM Audits 
CROSS JOIN (SELECT COUNT(1) ACount FROM Audits) ACount 
WHERE MONTH(TransActionDate) = MONTH(GETDATE()) 
GROUP BY Attribute, ACount 
ORDER BY COUNT(Attribute) DESC