Okay, I’m absolutely flummoxed trying to understand what’s going on here.
Everywhere I’m reading it is suggested to use MAX()/MIN() on a data column with a GROUP BY in order to get the highest/lowest value for each group of data. Yet every attempt I try to retrieve the data in such a way, it returns the max/min of one column, but then displays that data with the ID from a different row?!
I’ve distilled my query below to the simplest level, just the subscript that I’m trying to JOIN later with another larger query:
SELECT studentID, courseID, MAX(dateCreated) AS dateCreated
FROM courseAttempts
JOIN courses ON courseID = studentCourseID AND courseActive = 1
WHERE studentID IN (100,101,102,103) AND studentBlocked = 0
GROUP BY courseID
Below is the data that the script is able to retrieve without the use of MAX() or GROUP BY
studentID | courseID | dateCreated |
---|---|---|
100 | 39 | 2023-09-07 02:48:46.000 |
102 | 39 | 2023-12-24 02:57:07.000 |
If I run the script above with the MAX() and GROUP BY I get:
studentID | courseID | dateCreated |
---|---|---|
100 | 39 | 2023-12-24 02:57:07.000 |
That’s the right date, but the wrong ID. That’s malformed unusable data.
How is this supposed to work?