如何排列整个表的多列?

时间:2019-02-16 07:45:52

标签: 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个科目的排名。 输出不必采用我显示的格式。我只需要一个输出,指示每个学生每个学科的排名。 如何在SQLite中实现它?

我发现了RANK和ROW_NUMBER,但不知道如何将它们用于多列。

1 个答案:

答案 0 :(得分:4)

我的逻辑

  
      
  • 将列转换为行并通过并集获得得分列
  •   
  • rank()按学生划分以获得the ranks of all the 5 subjects for each individual student
  •   

模式(SQLite v3.26)

CREATE TABLE Table1
    ("student" TEXT(5), "physics" INTEGER, "chemistry" INTEGER, "maths" INTEGER, "history" INTEGER, "english" INTEGER)
;

INSERT INTO Table1
    ("student", "physics", "chemistry", "maths", "history", "english")
VALUES
    ('Brian', 78, 62, 100, 40, 50),
    ('Henry', 55, 72, 85, 22, 50)
;

查询

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   |

View on DB Fiddle