SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Join on Closest Date
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Brittney10
Posting Yak Master

USA
128 Posts

Posted - 06/22/2012 :  09:04:43  Show Profile  Reply with Quote
I have two tables: Invoice and Rates. I need to be able to join Invoice and Rates based on the Product and the Date. The only issue is that the Rates table does not contained every day (only a few days from any given month). so i can't do simple join based on the date (i.e. InvoiceDate = Date) What i need to do is join based on the closest date without going over.

For example:

Invoice:

Invoice....InvoiceDate.....Product
12345......01/10/2012......ASEAMN
67890......01/6/2012......JADMAE
09873......02/17/2012......ASEAMN

Rates:

Product.....Date..........Price
ASEAMN......01/01/2012.....10000
JADMAE......01/02/2012.....10231
ASEAMN......01/02/2012.....10050
JADMAE......02/01/2012....19999


How would i perform this join???

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 06/22/2012 :  14:30:36  Show Profile  Reply with Quote
;WITH cte AS
(
	SELECT i.*,rc.[Date] AS JoinDate
	FROM Invoice i
	CROSS APPLY
	(
		SELECT TOP (1) *
		FROM Rates r
		ORDER BY ABS(DATEDIFF(dd,i.[Date],r.[Date]))
	) rc
)
-- Your query here. Join cte to Rates table
-- on JoinDate column of cte and Dates column of Rates table
If you are simply trying to join the two tables, you can use the query inside the cte instead of making it a cte and joining again.

Edited by - sunitabeck on 06/22/2012 14:31:01
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000