SQL Server 2008:连接3个表并从子表中为每个父记录选择最后输入的记录

问题描述 投票:1回答:2

我有以下3个表,并且最后从理由表中针对索赔表中的每个claimno输入了原始代码。

原因:

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
sql sql-server sql-server-2008 max jointable
2个回答
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;

1
投票

你可以尝试使用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
© www.soinside.com 2019 - 2024. All rights reserved.