使用 SQL 服务器构建学生分数排序
Building a sorting of student marks using SQL Server
我的样本table:
student_name subject marks
a x 90
a y 95
b x 89
b y 99
c x 91
c y 96
我需要以学生的总和(分数)的方式输出,然后按降序排列。
例如a(90+95)=185,b(89+99)=188,c(91+96)=187
所以输出的顺序是:
student_name subject marks
b x 89
b y 99
c x 91
c y 96
a x 90
a y 95
我是 SQL 服务器的新手。你能帮我构建这个查询吗?
Select student_name, subject, marks
sum(marks) as total
from table order by total desc
这样做就可以了:
SELECT a.student_name
,a.subject
,a.marks
,(
SELECT sum(marks)
FROM TABLE b
WHERE a.student_name = b.student_name
GROUP BY b.student_name
)
FROM TABLE a
ORDER BY 4 DESC
,a.student_name
,a.marks ASC
您可以将 table 与每个学生的总分相加,然后按总分降序排列。
查询
select [t1].* from [your_table_name] as [t1]
join (
select [student_name], sum([marks]) as [total]
from [your_table_name]
group by [student_name]
) as [t2]
on [t1].[student_name] = [t2].[student_name]
order by [t2].[total] desc;
您可以在 order by
:
中使用 window 函数
Select student_name, subject, marks
from table
order by sum(marks) over (partition by student_name) desc,
student_name, subject;
注意 order by
中的附加键。当几个学生的总数相同时,这会使每个学生在一起。
如果您还想要结果中的总和:
Select student_name, subject, marks,
sum(marks) over (partition by student_name) as total_marks
from table
order by total_marks desc, student_name;
我的样本table:
student_name subject marks
a x 90
a y 95
b x 89
b y 99
c x 91
c y 96
我需要以学生的总和(分数)的方式输出,然后按降序排列。
例如a(90+95)=185,b(89+99)=188,c(91+96)=187
所以输出的顺序是:
student_name subject marks
b x 89
b y 99
c x 91
c y 96
a x 90
a y 95
我是 SQL 服务器的新手。你能帮我构建这个查询吗?
Select student_name, subject, marks
sum(marks) as total
from table order by total desc
这样做就可以了:
SELECT a.student_name
,a.subject
,a.marks
,(
SELECT sum(marks)
FROM TABLE b
WHERE a.student_name = b.student_name
GROUP BY b.student_name
)
FROM TABLE a
ORDER BY 4 DESC
,a.student_name
,a.marks ASC
您可以将 table 与每个学生的总分相加,然后按总分降序排列。
查询
select [t1].* from [your_table_name] as [t1]
join (
select [student_name], sum([marks]) as [total]
from [your_table_name]
group by [student_name]
) as [t2]
on [t1].[student_name] = [t2].[student_name]
order by [t2].[total] desc;
您可以在 order by
:
Select student_name, subject, marks
from table
order by sum(marks) over (partition by student_name) desc,
student_name, subject;
注意 order by
中的附加键。当几个学生的总数相同时,这会使每个学生在一起。
如果您还想要结果中的总和:
Select student_name, subject, marks,
sum(marks) over (partition by student_name) as total_marks
from table
order by total_marks desc, student_name;