如何计算一个百分比?在尝试根据行数计算百分比时,我得到了所有相同的值。我想要每个属性的百分比取决于COUNT的数量。因此,如果我将属性计数30次,我希望将其更改为百分比,具体取决于行数和其他值。
SELECT Attribute
, COUNT(Attribute) / COUNT(*) * 100 AS TopIssues
FROM Audits
WHERE MONTH(TransActionDate) = MONTH(GETDATE())
GROUP BY Attribute
ORDER BY COUNT(Attribute) DESC
答案 0 :(得分: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
答案 1 :(得分: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