I have this simple problem in SQL. I have a table with 4 columns. Columns being ID, DateTime, Decimal, AnotherID.
DECLARE @data DATETIME
SET @data = '20120101'
SELECT [ID]
,[Data]
,[Value]
,[InID]
FROM [dbo].[Static]
WHERE InID = 1 AND [Data] <= @data
Now I have to choose proper Value based on InID and Data. InID can have multiple rows with different dates. This is example output for InID = 1.
ID Data Value InID
389 2012-01-02 10.00000000 1
390 2011-12-16 20.00000000 1
391 2011-12-13 15.00000000 1
Now based on InID and Data I need to get Value for given date. For example for InID = 1 I need to get Value for day 2011-12-14. Of course the value should be taken from 13th of December and if I ask it about value for date 2012-01-13 it should take last value. However in case the question is about date before the first date it should return NULL. I tried multiple combinations but my brain seems to be out of order atm so any help would be appreciated.
Try this to get only the most recent
Valueconstrained by the@dataparameter:To the last part of your question if you need a
NULLresult you’ll have to wrap the query above as it will return an empty result set if nothing qualifies:The nearest would be this (just be aware that it can grab either future or past dates):