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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Max and Max-1 based on tables

Author  Topic 

tpavan7329
Starting Member

18 Posts

Posted - 2011-02-08 : 03:42:30

Table A has columns Phone Number and Post Date, data as below

PhoneNumber PostDate
123456 12/02/2010
123456 12/03/2010
456789 12/04/2010
456789 12/03/2010
456789 12/01/2010

Table B has columns phone number and Billing Date

Phone Number Billing Date
123456 11/20/2010
123456 11/11/2010
123456 11/10/2010
456789 11/02/2010
456789 10/10/2010
456789 11/30/2010


I want the result set as below

phone number post date billing date
123456 12/02/2010 11/11/2010
123456 12/03/2010 11/20/2010
and same for phone number 45678


Im trying to find a way to have a select statement based on below

From table data above, 123456 phone number has 2 different post dates,
step 1: To get max of post date(which is 12/03/2010) from table A for phone number 123456 and then move to table 2 to get max(billing date) which is 11/20/2010 for billing date in table c

Step 2:
For same phone number in table A 123456, i need to get second largest post date from table A for post date in table c and get the second largest billing date
from table b for table c billing date and so on...


Can you help me find a way to join both the table and match above steps scenarios?

Thanks
Pavan

djorre
Yak Posting Veteran

94 Posts

Posted - 2011-02-08 : 04:07:53
Maybe you can first become this table with row_number() over (partition by phone order by phone, postdate)

Nr PhoneNumber PostDate
1 123456 12/02/2010
2 123456 12/03/2010
1 456789 12/04/2010
2 456789 12/03/2010
3 456789 12/01/2010

Nr Phone Number Billing Date
1 123456 11/20/2010
2 123456 11/11/2010
3 123456 11/10/2010
1 456789 11/02/2010
2 456789 10/10/2010
3 456789 11/30/2010

then outer join that two query tables on Phone, Nr
Go to Top of Page
   

- Advertisement -