get latest record for each ID

前端 未结 3 1508
甜味超标
甜味超标 2021-01-28 01:16

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

Here is some example data:

TimeGenerated        SourceName            ComputerName  Message
2014-1         


        
3条回答
  •  天命终不由人
    2021-01-28 02:02

    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.

提交回复
热议问题