SQL 查询获得最高分数的主题

SQL query to get the subject with the max score

name    subject classroom   Total_Score  term   session 
jane     eng     phase1      79          1      2016/2017
jane     math    phase1      56          1      2016/2017
jane     eng     phase1      98          2      2016/2017
jane     math    phase1      87          2      2016/2017
jack     eng     phase1      94          1      2016/2017
jack     math    phase1      45          1      2016/2017
jack     eng     phase1      79          2      2016/2017
jack     math    phase1      89          2      2016/2017
jane     eng     phase2      55          1      2017/2018
jane     math    phase2      37          1      2017/2018
jack     math    phase2      45          1      2017/2018
jack     eng     phase2      59          2      2017/2018

嗨,我有这个 table,我正在尝试让学生在学期和课程中获得最高分的科目。预期结果应该类似于下面的 table

name   subject   classroom  max_score  term     session
jane     eng     phase1      79          1      2016/2017
jane     eng     phase1      98          2      2016/2017
jack     eng     phase1      94          1      2016/2017
jack     math    phase1      89          2      2016/2017
jane     eng     phase2      55          1      2017/2018
jack     eng     phase2      59          2      2017/2018

我尝试了以下查询

SELECT
  distinct name, subject, classroom, max(Total_Score), term, session
FROM
  ranktable
 group by name, classroom, term, session, subject
 order by term

但它没有 return 所需的输出。我将不胜感激我能得到的任何帮助。我对 SQL

比较陌生

跨数据库解决方案是使用相关子查询进行过滤:

select t.*
from mytable t
where t.total_score = (
    select max(t1.total_score)
    from mytable t1
    where 
        t1.name = t.name 
        and t1.term = t.term 
        and t1.session = t.session
)

这会为您提供 nametermsession 得分最高的行。

以下适用于 BigQuery 标准 SQL

#standardSQL
SELECT AS VALUE ARRAY_AGG(t ORDER BY Total_Score DESC LIMIT 1)[OFFSET(0)] 
FROM `project.dataset.table` t
GROUP BY name, classroom, term, session