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 |
Brittney10
Posting Yak Master
154 Posts |
Posted - 2012-06-22 : 09:04:43
|
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.....Product12345......01/10/2012......ASEAMN67890......01/6/2012......JADMAE09873......02/17/2012......ASEAMNRates:Product.....Date..........PriceASEAMN......01/01/2012.....10000JADMAE......01/02/2012.....10231ASEAMN......01/02/2012.....10050JADMAE......02/01/2012....19999How would i perform this join??? |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-06-22 : 14:30:36
|
[code];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[/code]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. |
|
|
|
|
|