简体   繁体   中英

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

I have following 3 tables and last entered reasoncode from Reasons table against each claimno in claims table.

Reasons:

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

Charges:

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

Claims:

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

Expected result would be like this:

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

I have applied many solutions but no luck. Following is the latest solution I was trying using SQL Server 2008 but still got incorrect result.

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

You can try using 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

Is this what you want?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM