sspeed
sspeed

Reputation: 19

get latest record for each ID

I would like to get the latest record for each server.

Here is some example data:

TimeGenerated        SourceName            ComputerName  Message
2014-11-22 21:48:30  Windows Update Agent  Server1       Update Failed
2014-11-22 21:42:30  Windows Update Agent  Server2       Update Failed
2014-11-22 21:45:30  Windows Update Agent  Server2       Update Failed
2014-11-22 21:43:30  Windows Update Agent  Server1       Update Failed

Desired Output:

TimeGenerated        SourceName            ComputerName  Message
2014-11-22 21:48:30  Windows Update Agent  Server1       Update Failed
2014-11-22 21:45:30  Windows Update Agent  Server2       Update Failed

I tried:

SELECT * FROM TABLE 
GROUP BY ComputerName 
ORDER BY TimeGenerated ASC 

But that outputs inconsistent results and does not give me the latest in most cases.

I also tried some sub queries, but failed miserably.

Upvotes: 0

Views: 162

Answers (3)

tvCa
tvCa

Reputation: 816

I you only use a GROUP function, you can only display the columns which are part of that SELECT statement. If you need more data displayed, you need to work with a subquery. For example, if you want to "select *", you can't just use only a GROUP BY and no subquery. So, it depends what you want to display.

Upvotes: 0

Marc B
Marc B

Reputation: 360572

SELECT *
FROM yourtable
INNER JOIN (
   SELECT MAX(timeGenerated) as maxtime, ComputerName
   FROM yourtable
   GROUP BY ComputerName
) AS latest_record ON (yourtable.timeGenerated = maxtime)
   AND (latest_record.ComputerName = yourtable.ComputerName)

Inner query gets the latest timestamp for every computer name. The outer query then joins against that query result to fetch the rest of the fields from the table, based on the time/computername the inner query finds. If you have two events logged with identical max times, you'd get two records for that computername.

Upvotes: 1

SMA
SMA

Reputation: 37023

Try this:

SELECT ComputerName, Max(date)
FROM TABLE
GROUP BY ComputerName

Upvotes: 0

Related Questions