2017-05-22 28 views
1

我有表記錄行的歷史記錄。我想獲得每一行的最新版本。它有,我可以使用 表中的記錄看起來像下面的時間戳: -抓取SQL表中的最新版本

5002113 691455384259 0 2 123111111 BG32 [email protected] 2017-05-18 15:12:40.967 
5002113 671797299758 0 2 12312311 BTY2 [email protected] 2017-05-15 14:42:53.690 
5002113 212212957483 0 2 1231412111 RTE  [email protected] 2017-05-14 16:16:59.110 
5002113 671797299758 0 2 123111111 BY32 [email protected]  2017-05-14 16:12:58.923 
5002113 691455384259 0 2 123111111 BIT32 [email protected] 2017-05-14 14:35:25.333 
5003183 594534755753 1 2 555555555 LS42 [email protected] 2017-05-12 17:42:20.457 
5002114 594534755753 1 2 234324121 fIS72 [email protected] 2017-05-12 17:35:20.527 

查詢: -

Select 
    ac.strID, 
    sp.strPin, 
    sp.blnActive, 
    CASE 
    WHEN strType = 'Email' and strRType = 'Email' THEN 2 
    WHEN strType = 'Paper' and strRType = 'Email' THEN 0 
    WHEN strType = 'Ws' and strRType = 'Ws' THEN 1 
    END as strInterfaceType, 
    id.strID, 
    sp.strFXType, 
    sp.strEmail, 
    sp.dtmChanged 
from employer_profile sp 
inner join employer_id id 
    on sp.lngCkey = id.LNGCKEY 
Inner join employer_account ac 
    on sp.lngAKey = ac.lngKey 
order by dtmChanged desc 

最終結果想: -

5002113 691455384259 0 2 123111111 BG32 [email protected] 2017-05-18 15:12:40.967 
5003183 594534755753 1 2 555555555 LS42 [email protected] 2017-05-12 17:42:20.457 
5002114 594534755753 1 2 234324121 fIS72 [email protected] 2017-05-12 17:35:20.527 
+0

MySQL或SQL服務器? – scsimon

回答

1

只需添加一個內部聯接

inner join 
(select max(dtmChanged) ts from employer_profile) t on t.ts = sp.dtmChanged 
1

您可以使用頂部1如下關係:

Select top (1) with ties * from 
(
    ...--your query without order by clause 
) a 
order by row_number() over(partition by strID order by dtmChanged desc) 

包括查詢,如下:

Select top (1) with ties * from 
(
    Select 
     ac.strID, 
     sp.strPin, 
     sp.blnActive, 
     CASE 
     WHEN strType = 'Email' and strRType = 'Email' THEN 2 
     WHEN strType = 'Paper' and strRType = 'Email' THEN 0 
     WHEN strType = 'Ws' and strRType = 'Ws' THEN 1 
     END as strInterfaceType, 
     id.strID, 
     sp.strFXType, 
     sp.strEmail, 
     sp.dtmChanged 
    from employer_profile sp 
    inner join employer_id id 
     on sp.lngCkey = id.LNGCKEY 
    Inner join employer_account ac 
     on sp.lngAKey = ac.lngKey 
) a 
order by row_number() over(partition by strID order by dtmChanged desc)