In SQL Server 2008, I want to join two table on key that might have duplicate, but the match is unique with the information from other columns.
For a simplified purchase record example,
Table A:
UserId PayDate Amount
1 2015 100
1 2010 200
2 2014 150
Table B:
UserId OrderDate Count
1 2009 4
1 2014 2
2 2013 5
Desired Result:
UserId OrderDate PayDate Amount Count
1 2009 2010 200 4
1 2014 2015 100 2
2 2013 2014 150 5
It's guaranteed that:
Table A and Table B have same number of rows, and
UserId
in both table are same set of numbers.For any
UserId
,PayDate
is always later thanOrderDate
Rows with same
UserId
are matched by sorted sequence ofDate
. For example, Row 1 in Table A should match Row 2 in Table B
My idea is that on both tables, first sort by Date
, then add another Id
column, then join on this Id
column. But I not authorized to write anything into the database. How can I do this task?