How are you defining nearest? Within what interval? In other words, has to be within a month ago or in the future or within a month either way or etc...
Main Topics
Browse All TopicsHi. I'm trying to retrieve the unique ID's closest to today's date. So only ID's 1,2,3 that have the newest dates. See table below. Thanks.
--------------------------
myDate ID
--------------------------
4/02/2009 12:00:00 AM 1
1/05/2009 12:00:00 AM 1
3/07/2009 12:00:00 AM 3
6/07/2009 12:00:00 AM 3
8/07/2009 12:00:00 AM 1
8/07/2009 12:00:00 AM 2
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
here are how you can find the dates closest to the current date...
select case when datediff(d, mindate, convert(varchar(10), getdate(), 101)) > datediff(d, maxdate, convert(varchar(10), getdate(), 101)) then maxdate else mindate end
from (
select as mindate = max(mydate) from tablename
where mydate < convert(varchar(10), getdate(), 101),
select as maxdate= min(mydate) from tablename
where mydate > convert(varchar(10), getdate(), 101)
) a
I would agree. That is a whole lot of code to just get ID and max date per ID which seems like what you wanted. You would use the accepted approach if you had additional columns of data necessary that could not be aggregated. If all you have is the column or columns that you are grouping by and columns that need aggregation like max(date) then http:#24799688 is much simpler (KISS principle).
Business Accounts
Answer for Membership
by: mrjoltcolaPosted on 2009-07-07 at 17:19:43ID: 24799682
Assuming all dates are in the past, this should work.
select id, max(myDate) from tbl
group by id;