如何解决最新记录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来自我要加入的tableB。
这是我当前正在尝试的查询,但是记录重复:
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,t2.InvID
我只需要每个VehID的最新记录。谢谢
解决方法
打开选项是使用子查询进行过滤:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。