I wanted to know how to use two max function in a query, i have this query
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). 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.
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
.
You can find more information about the Window functions here .
For your query to work, you need the maximum of the sy
/ sem
combination, not individually. 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.