I have two tables that I am trying to join in a query, but I’m having some difficulty getting the required output.
Table: Scans
ScanId ScanTime
1 8:00
2 8:15
3 9:00
4 9:30
6 10:00
7 10:45
8 11:00
9 11:10
Table: Responses
ScanId RespA RespB
3 ABC X
7 DEF Y
9 GHI Z
There is a foreign key on Responses.ScanId that references Scans.ScanId.
The Responses table may or may not have a corresponding row for each row in the Scans table.
What I need to do is produce the output shown below, each row in the Scans table is returned with the most recent previous response values.
For Scans.ScanId 1 and 2, there is no previous response so the Response columns are null.
For Scans.ScanId 3, 4 and 6, the most recent previous RespA is ABC and RespB is X (ScanId=3)
For Scans.ScanId 7 and 8, the most recent previous RespA is DEF and RespB is Y (ScanId=7)
For Scan.ScanId 9, the most recent previous RespA is GHI and RespB is Z (ScanId=9)
Desired Output:
ScanId ScanTime RespScanId RespA RespB
1 8:00 NULL NULL NULL
2 8:15 NULL NULL NULL
3 9:00 3 ABC X
4 9:30 3 ABC X
6 10:00 3 ABC X
7 10:45 7 DEF Y
8 11:00 7 DEF Y
9 11:10 9 GHI Z
I’m having difficulty figuring out how to write the join clause for this one. It needs to run on Sql Server 2005 and above.
Here’s a solution using a CTE…