Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2012-02-15 : 10:42:51
|
| Hi All - I have the following two tables which I am joining ...TABLE_1CellNumber416555123441655512354165551236TABLE_2CellNumber | AREA | DATE4165551234 01 01/05/2012 4165551234 02 12/05/20114165551234 03 02/05/20124165551235 01 01/05/2012 4165551235 02 12/05/20114165551235 03 02/05/20124165551236 10 01/05/2012 4165551236 11 12/05/20114165551236 12 02/05/2012I am doing a LEFT JOIN based on the CellPhone number. In the second table, CellNumber is duplicated. I ONLY want it to join based on the MOST RECENT date for that CELLNumber. How can I achieve this with the existing code?[CODESELECT T1.Cell_Number, T2.AREA FROM TABLE_1 T1LEFT JOIN TABLE_2 T2 ON T1.CellNumber = T2.Cell_Number[/CODE]I would like the output as follows:CellNumber AREA 4165551234 034165551235 02 4165551236 12 |
|
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2012-02-15 : 10:55:07
|
SELECT T1.Cell_Number, T2.AREA FROM TABLE_1 T1left join (select row_number() over (partition by CellNumber order by [DATE] DESC)as rnum,* from TABLE_2)as t2ON T1.CellNumber = T2.Cell_Number and t2.rnum=1 No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2012-02-15 : 11:11:40
|
| Worked like a charm, THANKS SO MUCH! |
 |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2012-02-16 : 11:43:33
|
| You're didn't work Brett, because t1.DATE does not exist.DATE only exists in T2.I appreciate you trying! |
 |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
|
|
|