Question : Grouping in SQL Select

I am trying to return a select statement to bring back the latest entry in an events table. The following is bringing back multiple user entries from the Events table. If I remove the tblEvent.UserName field is works fine.  So this works;

SELECT MAX(tblEvent.EventTime) AS EventTime,tblFolder.FolderID
FROM tblFolder,tblEvent
WHERE tblFolder.FolderID = tblEvent.FolderID
GROUP BY tblFolder.FolderID
ORDER BY tblFolder.FolderID

BUT this doesn't; I want the latest entry from tblEvents and then show a combination of fields from the two tables.
By adding the UserName reference there are multiple entries on the user. I just want the most recent based on EventTime.

SELECT MAX(tblEvent.EventTime) AS EventTime,tblFolder.FolderID,tblEvent.UserName
FROM tblFolder,tblEvent
WHERE tblFolder.FolderID = tblEvent.FolderID
GROUP BY tblFolder.FolderID,tblEvent.UserName
ORDER BY tblFolder.FolderID

The key field is FolderID, should I try HAVING IN or something?

Thx guys

Answer : Grouping in SQL Select

You can also move the max check to where clause:
1:
2:
3:
4:
5:
6:
7:
8:
9:
SELECT f.FolderID, e.UserName, e.EventTime
FROM tblFolder f
INNER JOIN tblEvent e ON e.FolderID = f.FolderID
WHERE e.EventTime = (
        SELECT MAX(tblEvent.EventTime)
        FROM tblEvent m
	WHERE m.FolderID = e.FolderID
) 
ORDER BY f.FolderID
Open in New Window Select All
Random Solutions  
 
programming4us programming4us