Select the latest record for each category linked available on an object

Posted by Simpleton on Stack Overflow See other posts from Stack Overflow or by Simpleton
Published on 2010-04-28T00:20:54Z Indexed on 2010/04/28 0:23 UTC
Read the original article Hit count: 614

I have a tblMachineReports with the columns: Status(varchar),LogDate(datetime),Category(varchar), and MachineID(int).

I want to retrieve the latest status update from each category for every machine, so in effect getting a snapshot of the latest statuses of all the machines unique to their MachineID.

The table data would look like

Category - Status - MachineID - LogDate
cata - status1 - 001 - date1
cata - status2 - 002 - date2
catb - status3 - 001 - date2
catc - status2 - 002 - date4
cata - status3 - 001 - date5
catc - status1 - 001 - date6
catb - status2 - 001 - date7
cata - status2 - 002 - date8
catb - status2 - 002 - date9
catc - status2 - 001 - date10


Restated, I have multiple machines reporting on multiple statuses in this tblMachineReports. All the rows are created through inserts, so their will obviously be duplicate entries for machines as new statuses come in. None of the columns can be predicted, so I can't do any ='some hard coded string' comparisons in any part of the select statement.


For the sample table I provided, the desired results would look like:

Category - Status - MachineID - LogDate
catc - status2 - 002 - date4
cata - status3 - 001 - date5
catb - status2 - 001 - date7
cata - status2 - 002 - date8
catb - status2 - 002 - date9
catc - status2 - 001 - date10

What would the select statement look like to achieve this, getting the latest status for each category on each machine, using MS SQL Server 2008? I have tried different combinations of subqueries combined with aggregate MAX(LogDates)'s, along with joins, group bys, distincts, and what-not, but have yet to find a working solution.

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about sql-server-2008