SQL 服务器 2008:将来自子 table 的 3 table 和 select 最后输入的记录加入每个父记录

SQL server 2008: join 3 tables and select last entered record from child table against each parent record

我有以下 3 table 和最后输入的原因代码来自 Reasons table 针对每个 claimno 索赔 table.

原因:

Rid  |chargeid|  enterydate    user   reasoncode
-----|--------|-------------|--------|----------
1    | 210    | 04/03/2018  | john   | 99 
2    | 212    | 05/03/2018  | juliet | 24
5    | 212    | 26/12/2018  | umar   | 55 
3    | 212    | 07/03/2018  | borat  | 30
4    | 211    | 03/03/2018  | Juliet | 20
6    | 213    | 03/03/2018  | borat  | 50
7    | 213    | 24/12/2018  | umer   | 60
8    | 214    | 01/01/2019  | john   | 70

费用:

chargeid |claim# | amount 
---------|-------|---------
210      | 1     | 10
211      | 1     | 24.2
212      | 2     | 5.45
213      | 2     | 76.30
214      | 1     | 2.10

索赔:

claimno | Code  | Code 
--------|-------|------
1       | AH22  | AH22 
2       | BB32  | BB32

预期结果是这样的:

claimno | enterydate  | user   | reasoncode
--------|-------------|--------|-----------
1       | 01/01/2019  | john   | 70
2       | 26/12/2018  | umer   | 55

我应用了很多解决方案,但没有成功。以下是我尝试使用 SQL Server 2008 但仍然得到不正确结果的最新解决方案。

With x As  
 (  
select r.chargeid,r.enterydate,ch.claimno from charges ch
join (select chargeid,max(enterydate) enterydate,user from Reasons group by chargeid) r on r.chargeid = ch.chargeid
)
select x.*,r1.user, r1.reasoncode from x
left outer join Reasons r1 on r1.chargeid = x.chargeid and r1.enterydate = x.enterydate
--group by x.claimno

您可以尝试使用 row_number()

select * from
(
select r.chargeid,r.enterydate,ch.claimno,user,reasoncode,
row_number() over(partition by ch.claimno order by r1.enterydate desc) as rn 
from charges ch left outer join Reasons r1 on r1.chargeid = ch.chargeid 
)A where rn=1

这是你想要的吗?

select claimno, enterydate, user, reasoncode
from (select c.claimno, r.*,
             row_number() over (partition by c.claimno order by r.entrydate desc) as seqnum
      from charges c join
           reasons r
           on c.chargeid = r.chargeid
     ) cr
where seqnum = 1;