我正在尝试获取pointsEarned
列的总和以及pointsPossible
列的总和。我想把它变成一个百分比。我的问题是我的SP总是返回0,即使有给定enrollmentId
的行具有前一列的值。
我做错了什么?
ALTER PROCEDURE GetPercentage
@enrollmentId int
AS
BEGIN
DECLARE @pointsEarned int;
DECLARE @pointsPossible int;
SET NOCOUNT ON;
SELECT
@pointsEarned = CAST(SUM(pointsEarned) OVER() AS decimal),
@pointsPossible = CAST(SUM(pointsPossible) OVER() AS decimal)
FROM
Assignments
WHERE
enrollmentId = @enrollmentId
RETURN @pointsEarned / @pointsPossible
END
GO
这是数据库表:
我执行存储过程并传入69的enrollmentId
,它仍然返回0.
答案 0 :(得分:2)
分母(pointsPossible
)大于分子(pointsEarned
)的整数除法返回零。
写为(修订):
ALTER PROCEDURE GetPercentage
@enrollmentId int
AS
BEGIN
SET NOCOUNT ON;
SELECT
Percent = case when sum(pointsPossible) > 0 then (1.0 * sum(pointsEarned)) / sum(pointsPossible) else 0 end
FROM
Assignments
WHERE
enrollmentId = @enrollmentId
GROUP BY
enrollmentId
END
GO
正如@ Nick.McDermaid指出的那样,由于此过程返回标量值,因此将其定义为函数而不是存储过程可能更合适。
答案 1 :(得分:1)
使用不含SUM
的简单OVER
。
RETURN
只能返回int
。如果您的百分比小于100%,整数除法将始终返回0,因此乘以100以返回整数百分比而不是比率。
检查您是否没有除以零。
<强>程序强>
ALTER PROCEDURE GetPercentage
@enrollmentId int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @pointsEarned int;
DECLARE @pointsPossible int;
SELECT
@pointsEarned = SUM(pointsEarned),
@pointsPossible = SUM(pointsPossible)
FROM
Assignments
WHERE
enrollmentId = @enrollmentId
;
RETURN
CASE WHEN @pointsPossible <> 0
THEN 100 * @pointsEarned / @pointsPossible
ELSE 0 END;
END
GO