Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select Max Date with Multiple records

I am struggling with a query to pull most recent entries. I have a Notes table that contains the following columns:

BusinessDate
ReportGuid
NoteGuid
Note
NoteDate
NoteAddedBy

The BusinessDate, ReportGuid and NoteGuid are the PK on the table. This table allows a specific ReportGuid to have multiple notes per day. I have another table that contains additional Report info that will be joined and displayed for the users. I am trying to pull and display only the most recent note entry for each ReportGuid.

I tried using Max(NoteDate) but that is only getting me the latest note added to the table not the latest note for each ReportGuid.

Any help would be appreciated.

Thanks

UPDATE:

thanks for the help:

SELECT N.Note, N.ReportGuid
FROM Tracking.SM_T_Report_Notes N
RIGHT OUTER JOIN
    (
    SELECT ReportGuid, Max(NoteDate) As NoteDate
    FROM Tracking.SM_T_Report_Notes
    GROUP BY ReportGuid
    ) AS ND
    ON  N.NoteDate = ND.NoteDate
like image 559
Taryn Avatar asked Jan 27 '11 13:01

Taryn


People also ask

Can Max function be used with date in SQL?

MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.

How do I get the maximum date between two columns in SQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields.

How do I select 3 max values in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.


1 Answers

You need to group by ReportGuid and select Max(NoteDate). That will select the maximum of each group.

like image 55
Adrian Grigore Avatar answered Sep 23 '22 09:09

Adrian Grigore