简体   繁体   English

在SQL中选择两个最大查询

[英]Selecting two max queries in sql

I wanted to know how to use two max function in a query, i have this query 我想知道如何在查询中使用两个max函数,我有这个查询

SELECT g.studentid, g.blockcode, sb.subjectcode, sb.daystart, sb.dayend, sb.stime, sb.sday, ii.firstname instructorname,  ii.lastname instructorlastname, sb.roomcode, r.building, d.description, rr.studentid,rr.sem, rr.sy
            FROM grades g 

            JOIN subjectblocking sb ON g.blockcode=sb.blockcode
            JOIN instructorinfo ii ON sb.instructorid=ii.instructorid
            JOIN subjects d ON sb.subjectcode = d.subjectcode
            JOIN room r ON sb.roomcode=r.roomcode
            JOIN register rr ON rr.studentid=g.studentid
            WHERE g.studentid='2011-S1308'
            AND rr.sem=(SELECT max(sem) from register
            WHERE sy= (SELECT max(sy) from register))
            ORDER BY  sb.daystart ASC, sb.stime like '%AM%' DESC;

the reason why I used two max because I want both semester and school year on max, so that student can view their schedule on what is current.How should i max them at the same time? 我之所以要使用两个最大值,是因为我希望学期和学年都达到最大值,以便学生可以查看当前进度表。我应该如何同时使其达到最大值? Also, the problem in my query is that only 1 max works, the max(sem). 另外,我的查询中的问题是只有1个max有效,即max(sem)。 Thank you in advance! 先感谢您!

What you need is to use 您需要使用

MAX(your_column) OVER (PARTITION BY semester_column) max_by_semester
MAX(your_column) OVER (PARTITION BY year_column) max_by_year

In this way you will get the MAX value for that slice of your data selected by the column value selected by the PARTITION BY clause. 这样,您将获得由PARTITION BY子句选择的列值选择的数据切片的MAX值。

Used in this way MAX is not an aggregate function but a window function, the behaviour is quite different and you don't need the Group By . 以这种方式使用MAX并不是一个聚合函数,而是一个窗口函数,其行为完全不同,您不需要Group By

You can find more information about the Window functions here . 您可以在此处找到有关Window功能的更多信息。

For your query to work, you need the maximum of the sy / sem combination, not individually. 为了使查询正常工作,您需要最大的sy / sem组合,而不是单独使用。 I think the query would look like: 我认为查询看起来像:

SELECT g.studentid, g.blockcode, sb.subjectcode, sb.daystart, sb.dayend, sb.stime, sb.sday,
       ii.firstname instructorname, ii.lastname instructorlastname,
       sb.roomcode, r.building, d.description, rr.studentid, rr.sem, rr.sy
FROM grades g JOIN
     subjectblocking sb
     ON g.blockcode = sb.blockcode JOIN
     instructorinfo ii
     ON sb.instructorid = ii.instructorid JOIN
     subjects d
     ON sb.subjectcode = d.subjectcode JOIN
     room r
     ON sb.roomcode = r.roomcode JOIN
     register rr
     ON rr.studentid = g.studentid
WHERE g.studentid = '2011-S1308' AND
      (sy, rr.sem) = (select sy, sem from register order by sy desc, sem desc limit 1)
ORDER BY sb.daystart ASC, sb.stime like '%AM%' DESC;

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

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