简体   繁体   English

带有最高值的 SQL 查询

[英]SQL query with Highest value with tie

I am trying to write a query that lists students who have earned the highest total credit in each department.我正在尝试编写一个查询,列出在每个部门获得最高总学分的学生。 I have to also include tied students in the result.我还必须在结果中包括并列学生。 The query should return relation with department name, student name and total credit they earned.查询应返回与部门名称、学生姓名和他们获得的总学分的关系。

SELECT s.dept_name, s.name, s.max
FROM (SELECT dept_name, name, MAX(tot_cred) as max 
      FROM university.student GROUP BY dept_name) as s,
     university.student as t
WHERE s.name = t.name;

It is giving errors and I don't know how to deal with ties.它给出了错误,我不知道如何处理关系。 If I delete the name part in the query, I have managed to get the highest credits in each department(without a tie)如果我删除查询中的姓名部分,我已经设法获得了每个部门的最高学分(没有并列)

The table student consists of an ID, name, department, total credit.表 student 由 ID、姓名、部门、​​总学分组成。

Use RANK() window function:使用RANK()窗口函数:

SELECT t.dept_name, t.name, t.tot_cred
FROM (
  SELECT dept_name, name, tot_cred, 
    RANK() OVER(PARTITION BY dept_name ORDER BY tot_cred DESC) rn
  FROM university.student 
) t
WHERE t.rn = 1

This is an alternative in case you can't use window functions:如果您不能使用窗口函数,这是一种替代方法:

SELECT s.dept_name, s.name, s.tot_cred
FROM university.student s
INNER JOIN (
  SELECT dept_name, MAX(tot_cred) tot_cred
  FROM university.student
  GROUP BY dept_name
) t ON t.dept_name = s.dept_name AND s.tot_cred = t.tot_cred

or with NOT EXISTS :NOT EXISTS

SELECT s.dept_name, s.name, s.tot_cred 
FROM university.student s 
WHERE NOT EXISTS (
  SELECT 1 FROM university.student
  WHERE dept_name = s.dept_name AND tot_cred > s.tot_cred  
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM