2017-05-22 4 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 Serverの? – 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) 
関連する問題