如何求和返回多行的选择的结果

时间:2009-12-23 01:47:19

标签: sql-server tsql sql

我有一个SQL变量@SumScore dec(9,4)

我正在尝试按如下方式分配变量:

SET @SumScore =   
        (  
            SELECT Sum(  
                (  
                    SELECT SUM(etjs.CalculatedScore * sc.PercentOfTotal) as CategoryScore   
                    FROM tblEventTurnJudgeScores etjs 
                        INNER JOIN tblJudgingCriteria jc ON  jc.JudgingCriteriaID = etjs.JudgingCriteriaID  
                        INNER JOIN tblScoringCategories sc ON jc.ScoringCategoryID = sc.ScoringCategoryID  
                    GROUP BY jc.JudgingCriteriaID  
                ) 
            As ComputedScore) AS SumTotalScore  
        )  

换句话说,内部选择返回一列。我希望为var分配正在返回的所有行的SUM。

我意识到这可以通过临时表很容易地完成。但这是唯一的方法吗?

3 个答案:

答案 0 :(得分:2)

SELECT Sum(CategoryScore)
FROM ( subquery )

答案 1 :(得分:1)

使用:

SET @SumScore = SELECT SUM(etjs.CalculatedScore * sc.PercentOfTotal) as CategoryScore   
                  FROM tblEventTurnJudgeScores etjs 
                  JOIN tblJudgingCriteria jc ON  jc.JudgingCriteriaID = etjs.JudgingCriteriaID  
                  JOIN tblScoringCategories sc ON jc.ScoringCategoryID = sc.ScoringCategoryID 

如果外部查询无论如何要总结所有内容,那么使用GROUP BY jc.JudgingCriteriaID是没有意义的。

答案 2 :(得分:0)

这对我有用:

select sum(myColumn) from MyTable where MyTableID = 'some value'

您也可以这样做(以使其更强大):

select sum(isnull(myColumn,0)) from MyTable where MyTableID = 'some value'