I have 2 tables from which I need to fetch unique records. When the condition don't match I need to get the next valid value.
Table A -
| RefNo | Enddate | StartDate | 
|---|---|---|
| 1234 | 20071010 | 20070618 | 
| 1234 | 20051021 | 20050627 | 
| 1234 | 20060608 | 20060220 | 
Table B -
| RefNo | CompareDate | FirstName | LastName | 
|---|---|---|---|
| 1234 | 19680611 | John | Smith | 
| 1234 | 20060220 | John | Mason | 
| 1234 | 20070618 | John | Smith | 
Result should be -
| RefNo | Enddate | Startdate | Firstname | Lastname | 
|---|---|---|---|---|
| 1234 | 20071010 | 20070618 | John | Smith | 
| 1234 | 20051021 | 20050627 | John | Mason | 
| 1234 | 20060608 | 20060220 | John | Mason | 
My current query is
SELECT RN = ROW_NUMBER() OVER (ORDER BY A.Refno), A.Refno, A.Startdate, A.Firstname, A.Lastname, A.EndDate
  FROM Table A A
  LEFT JOIN Table B b
  ON A.Refno = B.Refno
  WHERE A.Startdate BETWEEN B.StartDate AND B.Enddate
My current result is
| RN | Refno | StartDate | Firstname | Lastname | Enddate | 
|---|---|---|---|---|---|
| 1 | 01000184 | 20070618 | John | Smith | 20071010 | 
| 2 | 01000184 | 20060220 | John | Mason | 20060608 | 
Is it possible to get my results without stored procedure? Appreciate any assistance.
I need to fetch firstname, Lastname from one table if the start and end date is inbetween the startdate. I am getting when the condition match but I need all 3 rows with Firstname and Lastname from another row.
 
    