I was hoping someone could help me with this. I have two tables that need to be attached to the nearest date (closest to the date). I found with some search a way to do this using the DATEDIFF and Row_Number functions, but the result is not quite what I want. Here is what I am trying to do:
CREATE TABLE
INSERT INTO
( '2015-02-09',29540.3,12),
('2015-02-16',29661.7, 10),
('2015-03-02',29993.7,10),
('2015-03-09',30161.7,12),
('2015-03-16',30333.4,12),
('2015-03-23',30337.9,5),
('2015-03-30',30506.9,12),
('2015-04-06',30628.1,6),
('2015-04-13',30795,4),
('2015-04-20',30961.2,6)
SELECT * FROM
CREATE TABLE
INSERT INTO
('2015-03-05', 1000),('2015-03-27', 1040), ('2015-04-17', 1070)
;WITH Nearest_date AS
(
SELECT
t1.*, t2.Date as date2, t2.Value,
ROW_NUMBER() OVER
(
PARTITION BY t1.[Date]
ORDER BY t2.[Date] DESC
) AS RowNum
FROM
LEFT JOIN
ON t2.[Date] <= t1.[Date]
)
SELECT *
FROM Nearest_date
WHERE RowNum = 1
ORDER BY Date ASC
Date Runtime INTERVAL date2 Value
2/9/2015 29540.3 12 NULL NULL
2/16/2015 29661.7 10 NULL NULL
3/2/2015 29993.7 10 NULL NULL
3/9/2015 30161.7 12 3/5/2015 1000
3/16/2015 30333.4 12 3/5/2015 1000
3/23/2015 30337.9 5 3/5/2015 1000
3/30/2015 30506.9 12 3/27/2015 1040
4/6/2015 30628.1 6 3/27/2015 1040
4/13/2015 30795 4 3/27/2015 1040
4/20/2015 30961.2 6 4/17/2015 1070
Date Runtime INTERVAL date2 Value
2/9/2015 29540.3 12 NULL NULL
2/16/2015 29661.7 10 NULL NULL
3/2/2015 29993.7 10 NULL NULL
3/9/2015 30161.7 12 3/5/2015 1000
3/16/2015 30333.4 12 NULL NULL
3/23/2015 30337.9 5 NULL NULL
3/30/2015 30506.9 12 3/27/2015 1040
4/6/2015 30628.1 6 NULL NULL
4/13/2015 30795 4 NULL NULL
4/20/2015 30961.2 6 4/17/2015 1070
You can see that I want to select the nearest date indicated compared to all the dates in the second table. The query I created shows the same date for several values - when only one of these dates is really the closest. Any help will be, as always, massively appreciated. - launch of MSSQL 2014