ROW NUMBER LINKING based on date

  • Hi,

    Thanks in advance for anyone who helps but I thought I was quite a SQL expert but this issue has baffled me for a few days now and I can't seem to work out the best way to achieve a result.
    I have two tables:-

    Table ATable B
    EMPNOOCODESTARTDATEENDDATEROWNUMEMPNOCODESTARTDATEROWNUM
    1012253102739809-Apr-0231-Mar-0511012253A09-Apr-021
    1012253103138301-Apr-0514-Jan-0921012253B01-Apr-052
    1012253102739415-Jan-0924-Jan-1631012253F15-Jan-093
    1012253102642525-Jan-1641012253S01-Jan-124
    1012253V25-Jan-165

    I have used the row number in order to link Table A with Table B. And the link is fine for most scenarios. However i have noticed sometimes Table B has more rows then Table A and in the above scenario I would need to match Table B row 5 with table A row 4, Table B rownum 4 with Table A rownum 3 and so on based on the date.
    The problem I have is Table B could quite easily have 6 rows and Table A could have 4 rows and in this case I would need to link rownum 6 with rownum 4, rownum 5 with rownum 3 and so on.
    As you can see this is quite a tricky scenario and am not sure how best to tackle this.
    Thanks

  • If I'm correct, you effectively want to match the Maximum RowNum in Table A to the Maximum RowNum in Table B, and then work your way down, correct? Using a CTE, you could create a new Row Number to join on. Something like:
    WITH TableA AS (
      SELECT EMPNO, OCODE,STARTDATE, ENDDATE,ROWNUM,
            ROW_NUMBER() OVER (ORDER BY ROWNUM DESC) AS JOINID
      FROM [Table A])
    , TableB AS (
      SELECT EMPNO, CODE,STARTDATE,ROWNUM,
            ROW_NUMBER() OVER (ORDER BY ROWNUM DESC) AS JOINID
      FROM [Table B])
    SELECT *
    FROM TableA A
      JOIN TableB B ON A.JOINID = B.JOINID;

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Hi Thom,

    Thanks for your suggestion. Not sure if I've understood you correctly but that does not work as sometimes table B will have 6 rows and Table A will have 3 so rownum 6 will need to link with rown 3. Somehow the sql needs to say link the top 3 from Table A with the top 3 from Table B regardless of the row number. If that makes sense.

  • The above would work. If [Table A] has 3 rows, and [Table B] has 6, then the links would go (A -> B):
    1 -> 4
    2 -> 5
    3 -> 6

    From what you've posted, that seems correct to me. If not, provide DDL and DLM, along with expected results.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Hi Thom,
    Excellent. After a second look it certainly does work. Just what I needed. Also only needed a slight change to my current script.
    Thanks for your help.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply