2016-11-24 53 views
-1

的每一列嘿,我是新来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

是的。但是我只能得到一个专栏。如果有更多的专栏,我想知道如何去做? PostgreSQL中有什么能够返回表中的列数? – Mathew

回答

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;