我有这张表Student
:
- Id(int,主键标识)
- 名称(varchar(20))
- 得分(int)
- RecordDate(DateTime)
醇>
我需要选择此表的所有列以及一个代表' 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;
如何更改此查询?
答案 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;