Sql 如何对整个表的多个列进行排序?
我有一个SQLite表,其格式如下:Sql 如何对整个表的多个列进行排序?,sql,sqlite,Sql,Sqlite,我有一个SQLite表,其格式如下: student physics chemistry maths history english “学生”列有学生姓名,其他列有数字值,表示各个科目的分数。 我想了解每个学生的学科排名。 例如,对于行 Brian 78 62 100 40 50 我希望输出是 Physics - 2 Chemistry - 3 Maths - 1 History - 5 English - 4 这是每个学生所有5门学科的排名。 输出不必采用我显示的格式。我只需要一个输
student physics chemistry maths history english
“学生”列有学生姓名,其他列有数字值,表示各个科目的分数。
我想了解每个学生的学科排名。
例如,对于行
Brian 78 62 100 40 50
我希望输出是
Physics - 2
Chemistry - 3
Maths - 1
History - 5
English - 4
这是每个学生所有5门学科的排名。
输出不必采用我显示的格式。我只需要一个输出,表明每个学生的每个科目的排名。
如何在SQLite中实现它
我找到了排名和行号,但不知道如何将它们用于多列。我的逻辑
- 将列转换为行并通过union all获得分数列
- 按学生划分的排名(),以获得每个学生所有5门科目的排名
查询
with cte as (
select student,'physics' as class,physics as score from Table1 union all
select student,'chemistry' as class,chemistry as score from Table1 union all
select student,'maths' as class,maths as score from Table1 union all
select student,'history' as class,history as score from Table1 union all
select student,'english' as class,english as score from Table1
)
select student,class,score,RANK() OVER (partition by student order by score desc) rnk
from cte;
| student | class | score | rnk |
| ------- | --------- | ----- | --- |
| Brian | maths | 100 | 1 |
| Brian | physics | 78 | 2 |
| Brian | chemistry | 62 | 3 |
| Brian | english | 50 | 4 |
| Brian | history | 40 | 5 |
| Henry | maths | 85 | 1 |
| Henry | chemistry | 72 | 2 |
| Henry | physics | 55 | 3 |
| Henry | english | 50 | 4 |
| Henry | history | 22 | 5 |
with cte as (
select student,'physics' as class,physics as score from Table1 union all
select student,'chemistry' as class,chemistry as score from Table1 union all
select student,'maths' as class,maths as score from Table1 union all
select student,'history' as class,history as score from Table1 union all
select student,'english' as class,english as score from Table1
)
select student,class,score,RANK() OVER (partition by student order by score desc) rnk
from cte;
| student | class | score | rnk |
| ------- | --------- | ----- | --- |
| Brian | maths | 100 | 1 |
| Brian | physics | 78 | 2 |
| Brian | chemistry | 62 | 3 |
| Brian | english | 50 | 4 |
| Brian | history | 40 | 5 |
| Henry | maths | 85 | 1 |
| Henry | chemistry | 72 | 2 |
| Henry | physics | 55 | 3 |
| Henry | english | 50 | 4 |
| Henry | history | 22 | 5 |