如何在SQL Server 2008中汇总子查询数据?

时间:2013-09-08 04:54:49

标签: sql sql-server-2008-r2

如何在SQL Server 2008中汇总子查询数据?

在此查询中,我想在此Score函数中对此CASE列数据求和,其中数字范围之间的点,足够的时间我尝试对此列求和它显示错误。

现在,我想将此列ScoreGroup by Applicant id相加,我可以将Score列数据加在一起的方式是什么?

但是我不能这样做。请帮助我,这里我是初学者。

SELECT   
    ApplicantId, point,
    'Score' =  CASE 
                 WHEN  point BETWEEN 4.00 AND 4.50 THEN ('3' )
                 WHEN  point BETWEEN 3.5 AND 4.00 THEN ('2' ) 
              END
FROM tblAcademicInfo
WHERE tblAcademicInfo.ApplicantId = tblAcademicInfo.ApplicantId

输出:

ApplicantId  point   Score
--------------------------------
   xzc1  3.25    NULL
   xzc1  4.36    3
   xzc1  3.59    2
   xzc1  4.00    3

3 个答案:

答案 0 :(得分:1)

有几个问题

  1. 您的WHERE条款毫无意义
  2. 要求每位申请人使用SUM()GROUP BY条款
  3. 的总分
  4. 为了能够对值求和,您应该返回CASE中的数值而不是字符串文字
  5. 在您的查询中,您的选择中包含point列。但它不属于GROUP BY,因为您希望按applicantid进行分组。因此,您应该在此列上应用聚合函数(例如SUM())或从结果集中删除它。
  6. 尝试

    SELECT ApplicantId,
           SUM(CASE WHEN  point BETWEEN 4.0 AND 4.5 THEN 3
                    WHEN  point BETWEEN 3.5 AND 4.0 THEN 2 
           END) Score
      FROM tblAcademicInfo
     GROUP BY ApplicantId
    

    输出:

    | APPLICANTID | SCORE |
    |-------------|-------|
    |        xzc1 |     8 |
    

    这是 SQLFiddle 演示

答案 1 :(得分:0)

您是否尝试过以下操作:

SELECT   ApplicantId,point,
    SUM(CASE 
WHEN  point BETWEEN 4.00 AND 4.50 THEN 3
WHEN  point BETWEEN 3.5 AND 4.00 THEN 2 
END
) [Score]
FROM tblAcademicInfo
WHERE tblAcademicInfo.ApplicantId
GROUP BY ApplicantId, point

答案 2 :(得分:0)

试试这个

SELECT ApplicationId,Point,sum(Case When score IS Null Then 0 else score END) as SumScore
FROM tblAcademicInfo
GroupBy Applicatio0nId,Point,score