我有一个非常基本的SQL查询查询,它正在对从分组结果集返回的记录总数进行计算。
SELECT vco.OutcomeName,
vco.VersionCompareOutcomeID,
COUNT(t.OutcomeName) AS Total,
ROUND(COUNT(*) * 100.0 / sum(count(*)), 1) over() AS Percentage
FROM map.VersionCompareOutcome AS vco
LEFT JOIN @temp AS t
ON vco.VersionCompareOutcomeID = t.VersionCompareOutcomeID
GROUP BY vco.OutcomeName, vco.VersionCompareOutcomeID
当我尝试使用round
函数时,我收到以下错误:The function 'ROUND' is not a valid windowing function, and cannot be used with the OVER clause.
如果没有round
功能,我会得到百分比,但不像我想要的那样四舍五入。
我想要的结果是2位小数:例如87.95%
。
答案 0 :(得分:2)
您不能将ROUND
与OVER
一起使用,只能使用聚合,排名和分析功能。
但是,您可以在子查询或CTE中进行聚合,然后在外部查询中进行舍入:
WITH CTE
AS
(
SELECT vco.OutcomeName,
vco.VersionCompareOutcomeID,
COUNT(t.OutcomeName) AS Total
FROM map.VersionCompareOutcome AS vco
LEFT JOIN @temp AS t ON vco.VersionCompareOutcomeID = t.VersionCompareOutcomeID
GROUP BY vco.OutcomeName, vco.VersionCompareOutcomeID
)
SELECT
OutcomeName,
VersionCompareOutcomeID,
Total,
CASE WHEN (SELECT COUNT(*) FROM @temp) = 0 THEN 0 ELSE ROUND(Total * 100.0 / (SELECT COUNT(*) FROM @temp), 1) END AS Percentage
FROM CTE