Hi,I’m trying to write a query that will extract cost based on closest date (<= date passed by user), product and terminal from example below. Table has over million records. I was trying to utilize ROW_NUMBER()OVER(ORDER BY MarketDate) functionality but no luck because table can have multiple identical dates for same products Please help. SELECT PK, Terminal, MarketDate = CAST(d.MarketDate AS DATETIME) ,d.Prod, d.Cost INTO #TestTable FROM ( SELECT 1, 1, '2014-12-01 15:04:00.000','A', 2.23 UNION ALL SELECT 2, 1, '2014-12-04 00:04:00.000','A', 2.27 UNION ALL SELECT 3, 1, '2014-12-05 11:04:00.000','A', 2.34 UNION ALL SELECT 4, 2, '2014-12-01 15:04:00.000','A', 2.20 UNION ALL SELECT 5, 2, '2014-12-02 18:08:00.000','A', 2.31 UNION ALL SELECT 6, 1, '2014-12-01 15:04:00.000','B', 5.54 UNION ALL SELECT 7, 1, '2014-12-02 14:04:00.000','B', 5.64 UNION ALL SELECT 8, 2, '2014-12-03 12:12:00.000','B', 5.51 UNION ALL SELECT 9, 1, '2014-12-01 00:04:00.000','C', 7.23 UNION ALL SELECT 10,1, '2014-12-04 00:04:00.000','C', 6.22 UNION ALL SELECT 11,1, '2014-12-05 00:04:00.000','C', 6.23 UNION ALL SELECT 12,1, '2014-12-06 00:04:00.000','C', 6.24 UNION ALL SELECT 13,1, '2014-12-12 10:04:00.000','C', 3.99 ) d ( PK,Terminal,MarketDate, Prod, Cost);Expected result if user passes date MarketDate='2014-12-05 00:01:00.000'PK Terminal MarketDate Prod Cost2 1 2014-12-04 00:04:00.000 A 2.275 2 2014-12-02 18:08:00.000 A 2.317 1 2014-12-02 14:04:00.000 B 5.648 2 2014-12-03 12:12:00.000 B 5.5110 1 2014-12-04 00:04:00.000 C 6.22
↧