获取每个ID的最新记录
问题描述:
我想获得每个服务器的最新记录。获取每个ID的最新记录
下面是一些示例数据:
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
所需的输出:
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
我想:
SELECT * FROM TABLE
GROUP BY ComputerName
ORDER BY TimeGenerated ASC
但输出结果不一致,不给我最新的在大多数情况下。
我也尝试了一些子查询,但失败惨败。
答
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)
内查询获取最新的时间戳为每台计算机名称。然后,外部查询将与该查询结果连接,以基于内部查询找到的时间/计算机名称从表中获取剩余的字段。如果您有两个记录的最大时间相同的事件,那么您将获得该计算机名的两个记录。
答
我只使用GROUP函数,只能显示那些SELECT语句的一部分的列。如果您需要显示更多数据,则需要使用子查询。例如,如果你想“选择*”,你不能只使用一个GROUP BY,也不能使用子查询。所以,这取决于你想要显示的内容。
谢谢你,这是一个救生员,我让自己疯狂。 – sspeed 2014-11-24 17:40:20