;WITH cte AS
SELECT i.*,rc.[Date] AS JoinDate
FROM Invoice i
SELECT TOP (1) *
FROM Rates r
ORDER BY ABS(DATEDIFF(dd,i.[Date],r.[Date]))
-- Your query here. Join cte to Rates table
-- on JoinDate column of cte and Dates column of Rates tableIf 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.