【问题标题】:How to return the calculated (aggregated) result of a SQL Server stored procedure如何返回 SQL Server 存储过程的计算(聚合)结果
【发布时间】:2015-09-30 13:09:13
【问题描述】:

我正在尝试编写一个将返回一个数字(平均值)的存储过程 - 这就是我目前所拥有的......

ALTER PROCEDURE [dbo].[sp_GetAverageRating]
    @RecipeNodeId int 
AS 
    SET NOCOUNT ON;

    (SELECT SUM(Rating) AS RatingTotal
     FROM dbo.RecipeRating
     WHERE RecipeNodeId = @RecipeNodeId)

    (SELECT 
         COUNT(Rating) AS RatingEntries 
     FROM dbo.RecipeRating 
     WHERE RecipeNodeId = @RecipeNodeId)

所以这有效并给了我

A.) 总评分
B.) 评分条目数

我想从存储过程中返回 Rating Total / Rating Entries。

谁能帮我看看语法吗?

【问题讨论】:

标签: sql sql-server stored-procedures sum aggregate


【解决方案1】:

只需使用 AVG 功能:

SELECT AVG(Rating) as RatingTotal
FROM dbo.RecipeRating
WHERE RecipeNodeId = @RecipeNodeId

【讨论】:

  • 也许将它放在 UDF 中而不是 SPROC 中更有意义。 create function fnAvgRating(@RecipeNodeId int) returns decimal as select avg(Rating) from dbo.RecipeRating where RecipeNodeId = @RecipeNodeId
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
相关资源
最近更新 更多