Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
I need a query that gives me the value of a column on a certain date..
If that does not exist in the DB it needs to take the closest possible date ..

currently I have this


SQL
select A, min(B)
from Table1

where gebeurtenis between begindatum and einddatum

group by A



thanks in advance!
Posted
Updated 21-Aug-13 0:01am
v2

"Closest possible date" is a slightly nebulous concept here: is it closer if it's before, or after the desired date?

Probably, you are going to want to do something like:
SQL
SELECT TOP 1 * FROM myTable WHERE gebeurtenis >= '2013-01-01' ORDER BY gebeurtenis DESC
Or
SQL
SELECT TOP 1 * FROM myTable WHERE gebeurtenis <= '2013-01-01' ORDER BY gebeurtenis ASC

But there is no good mechanism for doing both at once.
 
Share this answer
 
Comments
Sam Van den Bossche 21-Aug-13 6:04am    
right, its the next date not the date before the given date
OriginalGriff 21-Aug-13 6:08am    
So you want the second one.
"Return the first date on or after the specified date"
check below example replace underlined portion with tablename
SQL
declare @begindatum datetime
set @begindatum = '2013-07-09'
select top 1 A, ABS(DateDiff(d,gebeurtenis,@begindatum)) nearbydays,gebeurtenis
from
(
SELECT 'a' as A, '2013-07-15' gebeurtenis
union all
SELECT 'a' as A, '2013-07-08' gebeurtenis
union all
SELECT 'a' as A, '2013-07-10' gebeurtenis
) as table1
order by  ABS(DateDiff(d,gebeurtenis,@begindatum))

Happy Coding!
:)
 
Share this answer
 
Comments
Mas11 21-Aug-13 6:11am    
Nice answer Aarti ! 5*
Aarti Meswania 21-Aug-13 6:39am    
Thank you! :)
create an sql function "CurentorNearestDate" and pass a code like this

SQL
select A, min(B)
from Table1

where gebeurtenis = CurentorNearestDate(gebeurtenis) 

group by A
 
Share this answer
 
v2
Comments
Mas11 21-Aug-13 6:11am    
Nice Try !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900