我有记录行历史的表。我想获得每一行的最新版本。它有我可以使用的时间戳 表记录如下所示: -
5002113 691455384259 0 2 123111111 BG32 che2ck@gmail.com 2017-05-18 15:12:40.967
5002113 671797299758 0 2 12312311 BTY2 che4ck@gmail.com 2017-05-15 14:42:53.690
5002113 212212957483 0 2 1231412111 RTE che3ck@gmail.com 2017-05-14 16:16:59.110
5002113 671797299758 0 2 123111111 BY32 check@gmail.com 2017-05-14 16:12:58.923
5002113 691455384259 0 2 123111111 BIT32 chec4k@gmail.com 2017-05-14 14:35:25.333
5003183 594534755753 1 2 555555555 LS42 tha3ur@gmail.com 2017-05-12 17:42:20.457
5002114 594534755753 1 2 234324121 fIS72 trtakur@gmail.com 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 che2ck@gmail.com 2017-05-18 15:12:40.967
5003183 594534755753 1 2 555555555 LS42 tha3ur@gmail.com 2017-05-12 17:42:20.457
5002114 594534755753 1 2 234324121 fIS72 trtakur@gmail.com 2017-05-12 17:35:20.527
答案 0 :(得分:1)
只需添加内部联接
inner join
(select max(dtmChanged) ts from employer_profile) t on t.ts = sp.dtmChanged
答案 1 :(得分: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)