最新记录MS SQL

Most recent record MS SQL(最新记录MS SQL)
本文介绍了最新记录MS SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需要最近的记录

当前数据:

RequestID   RequestCreateDate         VehID    DeviceNum   ProgramStatus   InvID
1           08/12/2018 13:00:00:212     110       20178      Submitted        A1
2           08/11/2018 11:12:33:322     110       20178      Pending          A1
3           09/08/2018  4:14:28:132     110       Null       Cancelled        A1
4           11/11/2019 10:12:00:123     188       21343      Open             B3
5           12/02/2019 06:15:00:321     188       21343      Submitted        B3
请求结果:

RequestID   RequestCreateDate         VehID    DeviceNum   ProgramStatus   InvID 
3           09/08/2018  4:14:28:132     110       Null       Cancelled        A1
5           12/02/2019 06:15:00:321     188       21343      Submitted        B3

InvID来自我要加入的表B。

以下是我当前正在尝试的查询,但存在重复记录:

Select 
    max(t1.RequestID) ReqID,
    max(t1.RequestCreateDate) NewDate,
    t1.VehID,
    t1.DeviceNum,
    t1.ProgramStatus,
    t2.InvID
FROM table1 t1
LEFT JOIN table2 t2 ON t1.VehID = t2.VehID
GROUP BY t1.VehID, t1.DeviceNum, t1.ProgramStatus, t2.InvID 
我只需要每个Vehid的最新记录。谢谢

推荐答案

On选项是使用子查询进行筛选:

select t1.*, t2.invid
from table1
left join table2 t2 on t1.vehid = t1.vehid
where t1.requestCreateDate = (
    select max(t11.requestCreateDate)
    from table1 t11
    where t11.vehid = t1.vehid
)

为提高性能,请考虑table1(vehid, requestCreateDate)上的索引。

您还可以使用row_number()

select *
from (
    select t1.*, t2.invid, row_number() over(partition by vehid order by requestCreateDate desc) rn
    from table1
    left join table2 t2 on t1.vehid = t1.vehid
) t
where rn = 1

这篇关于最新记录MS SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)