对表的每列进行排序

时间:2016-11-24 06:42:10

标签: postgresql

嘿,我是sql / postgreSql的新手。我遇到了问题,我想就如何做到这一点提出建议。下面是我给出的表格。

Student Maths   Physics Chemistry
Joe     80      52       69
Steff   50      90       95
James   62      98       42

我需要查询上表,以便根据标记按降序对学生进行排序。见下文。

Maths   Physcis Chemistry
Joe     James   Steff
James   Steff   Joe
Steff   Joe     James

提前致谢:)

1 个答案:

答案 0 :(得分:0)

答案的关键是window functions

with orders as (
    select
        student,
        row_number() over (order by maths desc) as m,
        row_number() over (order by physics desc) as p,
        row_number() over (order by chemistry desc) as c
    from ratings
)
select
    m.student as Maths,
    p.student as Physics,
    c.student as Chemistry
from orders as m
join orders as p on m.m=p.p
join orders as c on m.m=c.c
order by m.m;