通过总和计算密集排名

Calculate dense rank by sum

示例数据:

student marks subject
stud1 100 sub1
stud1 400 sub2
stud1 500 sub3
stud2 200 sub1
stud2 700 sub2
stud2 800 sub3
stud2 900 sub4
stud3 300 sub1
stud3 600 sub2
stud4 1000 sub1

尝试按学生划分并按分数总和排序,如下所示,使用 dense_rank()。还有多个其他列,由于数据很大,尽量避免在此处进行任何连接。

预期输出:

student marks subject ds_rnk
stud1 100 sub1 2
stud1 400 sub2 2
stud1 500 sub3 2
stud2 200 sub1 1
stud2 700 sub2 1
stud2 800 sub3 1
stud2 900 sub4 1
stud3 300 sub1 3
stud3 600 sub2 3
stud4 1000 sub1 2

提前致谢!

您可以分两个阶段计算 sum 和 dense_rank:

with cte as (
    select t.*, sum(marks) over (partition by student) as sum_marks
    from t
)
select cte.*, dense_rank() over (order by sum_marks desc) as dense_rankk
from cte