sql查询中的Sum函数

时间:2016-09-23 19:28:29

标签: sql aggregate-functions

我有这张表Student

  
      
  1. Id(int,主键标识)
  2.   
  3. 名称(varchar(20))
  4.   
  5. 得分(int)
  6.   
  7. RecordDate(DateTime)
  8.   

我需要选择此表的所有列以及一个代表' Sum'的额外列。分数'列取决于学生的Name

我尝试了这个,但它没有工作

select S.Id,S.Name ,S.Score ,S.RecordDate, ( select Sum(Score) from Student where Name= S.Name) as All_Student_Score
 from Student S;

如何更改此查询?

4 个答案:

答案 0 :(得分:1)

您可以尝试这样

select Id,Name ,Score ,RecordDate, sum(score) over(partition by name) as All_Student_Score from Student S

答案 1 :(得分:1)

You can use a `JOIN`:

    SELECT S.*,
           T.All_Student_Score
    FROM Student S
    INNER JOIN (SELECT Name, SUM(Score) All_Student_Score
                FROM Student) T
        ON S.Name = T.Name;

答案 2 :(得分:1)

以下解决方案适用于您的要求。

select Id, 
       Name,
       Score,
       RecordDate,
       sum(score) over( partition by name ) as All_Student_Score 
  from Student; 

答案 3 :(得分:1)

因为如果您只是在子查询中对表进行别名,没有人向您展示您自己的解决方案应该可以正常工作,您可以执行以下操作:

select
     S.Id,S.Name
     ,S.Score
     ,S.RecordDate
     ,(select Sum(Score) from Student s2 where s2.Name= S.Name) as All_Student_Score
from
     Student S;