2016-09-27 189 views
0

我已經加入兩張表來提取我需要的數據。我無法只從一張表中顯示最新的記錄。我想要做的是尋找最後更新的值。我試圖納入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 
+0

如果您可以顯示錶格具有哪些列,將會有所幫助。 –

+0

哪個表格包含所有更改的數據? – Teja

+0

請發佈您的模式,輸入和輸出 – Teja

回答

-1

如果您想獲得最後更新值,然後只是簡單地添加到您的查詢:

order by t2.updateddate desc 

它會顯示最當前記錄從表中。

1

你可以用,只是抓住每個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 

我加在你的tablePlan因爲這些用法括號是SQL保留字。