在sql中选择两个最大查询

时间:2015-02-09 10:54:51

标签: php sql postgresql codeigniter

我想知道如何在查询中使用两个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;

我之所以使用两个max是因为我希望学期和学年都达到最大,所以学生可以查看当前的时间表。我应该如何同时最大化它们?此外,我的查询中的问题是只有1 max工作,max(sem)。先感谢您!

2 个答案:

答案 0 :(得分:0)

您需要的是使用

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

通过这种方式,您将获得由PARTITION BY子句选择的列值选择的数据切片的MAX值。

以这种方式使用MAX不是一个聚合函数,而是一个窗口函数,行为完全不同,你不需要Group By

您可以找到有关窗口函数here的更多信息。

答案 1 :(得分:0)

要使您的查询生效,您需要sy / sem组合的最大值,而不是单独的组合。我认为查询看起来像:

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;