用于检索此分组数据的适当 SQL Server 方法?
我有一个表 (AU_EMPLOYEE),其中有两列,分别名为 EmployeeID (int) 和 LastModifiedDate (DateTime)。除了这些列之外,还有其他包含其他员工数据的列。这是一个审计表,每当员工的数据以某种方式发生更改时,就会添加新行。
因此,某个特定员工很可能在此表中拥有多行。我想检索由 LastModifiedDate 确定的每个员工的最新记录。这样做的好方法是什么?嵌套查询或类似的东西?
感谢您的建议。
I have a table (AU_EMPLOYEE) with two columns named EmployeeID (int) and LastModifiedDate (DateTime). Along with those columns are others containing additional employee data. This is an audit table and every time an employee's data changes in some way a new row is added.
So it's quite likely a given employee will have multiple rows in this table. I would like to retrieve the most recent record for each employee as determined by the LastModifiedDate. What is a good approach to doing this? Nested query or something along those lines?
Thanks for the suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用类似的方法来显示每个员工的最新行。这是 ROW_NUMBER 函数的一个很好的用途。
You could use something like this to show the most recent row for each employee. This is a good use for the ROW_NUMBER function.
假设至少是 SQL 2005,这样您就可以使用 CTE:
编辑:正如我所指出的这里和这里过去,一定要测试性能。具有 MAX 的 CTE 版本通常会优于基于 ROW_NUMBER 的解决方案。
Assuming at least SQL 2005 so you can use a CTE:
EDIT: As I've pointed out here and here in the past, be sure to test performance. The CTE version with MAX will often outperform a ROW_NUMBER based solution.
克里斯·佩布尔的回答是正确的
然而,更通用的解决方案是
X 是您想要返回的日期。
Chris Pebble's answer is correct
however a more general solution is
where X is the date you want to go back in time to.