如何显示多条记录的最新更新记录
问题描述:
我已经加入两张表来提取我需要的数据。我无法只从一张表中显示最新的记录。我想要做的是寻找最后更新的值。我试图纳入max()和row_num,但没有取得任何成功。如何显示多条记录的最新更新记录
这是我目前有:
select distinct t1.CaId,t1.Enrolled,t1.Plan,t2.Category,t2.updateddate
from table.one(nolock) t1
inner join table.two(nolock) t2 on t1.CaId=t2.CaID
where t1.coverageyear=2016
and right(t1.Plan,2)<>left(t2.Category,2)
order by 5 desc
答
如果您想获得最后更新值,然后只是简单地添加到您的查询:
order by t2.updateddate desc
它会显示最当前记录从表中。
答
你可以用,只是抓住每个ID的最后更新日期,像这样的子查询加入您的主查询:
select all_rec.CaId, all_rec.Enrolled, all_rec.[Plan], all_rec.Category, all_rec.updateddate
from
(select distinct t1.CaId,t1.Enrolled,t1.[Plan],t2.Category,t2.updateddate
from [table.one](nolock) t1
inner join [table.two](nolock) t2 on t1.CaId=t2.CaID
where t1.coverageyear=2016
and right(t1.[Plan],2)<>left(t2.Category,2)
) as all_rec
inner join
(SELECT max(updateddate) AS LAST_DATE, CaId
FROM [table.two](nolock)
GROUP BY CaId)
AS GRAB_DATE
on (all_rec.Ca_Id = GRAB_DATE.Ca_Id)
and (all_rec.updateddate = GRAB_DATE.updateddate)
order by 5 desc
我加在你的table
和Plan
因为这些用法括号是SQL保留字。
如果您可以显示表格具有哪些列,将会有所帮助。 –
哪个表格包含所有更改的数据? – Teja
请发布您的模式,输入和输出 – Teja