您好我可以知道如何获取SQL服务器中的最后更新记录 [英] Hi can I know how to fetch the last updated record in the SQL server

查看:72
本文介绍了您好我可以知道如何获取SQL服务器中的最后更新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子

1)Vechile Detials

2)跟踪表



可以任意一个帮助我如何获取所有车辆的最新记录。



我尝试过:



i have the two tables
1)Vechile Detials
2)Tracking table

Can any one help me how can i fetch the latest records of all the vehicles.

What I have tried:

select t.IMEINo,t.speed,t.Ignition,t.TrackTime,tblSATVehicles.VehicleNumber
from  Tracking t
inner join tblSATVehicles on t.IMEINo=tblSATVehicles.DeviceIMEI
inner join (
    select IMEINo, max(TrackTime) as maxtime
    from Tracking tm
    group by IMEINo
) tm on t.IMEINo = tm.IMEINo and t.TrackTime= tm.maxTime

推荐答案

获取最新数据的唯一可靠方法是为行添加时间戳当您插入或更新它们时:然后您可以使用ORDER BY timeStampColumn DESC以正确的顺序获取,并使用TOP 1来选择最新的项目。



如果你没有时间戳,那么你不能保证订购 - 这意味着你的DB可以按照它认为最合适的任何顺序返回行。连续两次不必是相同的顺序!
The only reliable way to fetch the latest data is to timestamp rows when you INSERT or UPDATE them: you can then use ORDER BY timeStampColumn DESC to get then in the right order, and TOP 1 to select just the latest item.

If you don't have a timestamp, then you cannot guarantee ordering - and that means your DB can return rows in any order it finds most appropriate. Which doesn't have to be the same order two times in a row!


也许你可以使用 OUTPUT 子句,但这不适用于select声明:

OUTPUT子句(Transact-SQL) - SQL Server | Microsoft Docs [ ^ ]
Maybe you can use the OUTPUT clause, but this does not work with a select statement:
OUTPUT Clause (Transact-SQL) - SQL Server | Microsoft Docs[^]


这篇关于您好我可以知道如何获取SQL服务器中的最后更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆