0

I have this table Student :

  1. Id (int , primary key identity)
  2. Name (varchar(20))
  3. Score (int)
  4. RecordDate (DateTime)

I need to select all the columns of this table plus an extra column that represents the 'Sum' of 'Score' column depending of the Name of the student.

I tried this but it didn't work

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;

How can I change this query ?

3
  • Dont mix up the databases Commented Sep 23, 2016 at 19:31
  • 1
    Are you looking this in SQL-Server or mysql or both? Commented Sep 23, 2016 at 19:33
  • @KannanKandasamy both Commented Sep 23, 2016 at 19:37

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

1

You can try like this

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

2 Comments

You are right, hadn't noticed it. But your query is still wrong though
Just noticing that he is asking sum for individual name.. thanks, since alias he mentioned as 'All_student_score' i got confused...
1

The below solution works for your requirement.

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

Comments

1

Because no one showed you that your own solution should work if you just alias your table in your sub query you can do the following:

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.