Solved

T-SQL Returning nearest date

Posted on 2009-07-07
11
1,067 Views
Last Modified: 2012-06-27
Hi. 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
0
Comment
Question by:helpdeskis
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24799682
Assuming all dates are in the past, this should work.

select id, max(myDate) from tbl
group by id;
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 24799686
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...
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24799688
If not, just add a where clause:

select id, max(myDate) from tbl
where myDate < getdate()
group by id;
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 24799689
Or possibly you meant max (newest) date for each ID like MrJoltCola showed.  That would make sense, especially if your date format above is dd/MM/yyyy versus MM/dd/yyyy as I thought it was.
0
 
LVL 60

Expert Comment

by:chapmandew
ID: 24799716
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
0
Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

 
LVL 25

Expert Comment

by:imitchie
ID: 24800175
Since you have posted in sql server 2005, here you go.
As you can see, I have put some comments in case you need to vary it slightly to suit your needs.
select ID, myDate

from (

	select rn=ROW_NUMBER() over (order by myDate desc)

	where myDate <= GETDATE() -- closest (on or before) current date(time)

) X

where rn = 1 -- only one record for each unique ID

Open in new window

0
 
LVL 25

Accepted Solution

by:
imitchie earned 500 total points
ID: 24800185
Apologies, I forgot to add the columns into the inner select.  You can add other columns just as easily.
select ID, myDate

from (

        select rn=ROW_NUMBER(), ID, myDate over (order by myDate desc)

        where myDate <= GETDATE() -- closest (on or before) current date(time)

) X

where rn = 1 -- only one record for each unique ID

Open in new window

0
 

Author Closing Comment

by:helpdeskis
ID: 31600951
Thanks,that gets the job done.
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24800643
Hi, I am not objecting, but I am curious why this solution was chosen over the other valid ones?

0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 24803251
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).
0
 

Author Comment

by:helpdeskis
ID: 24809704
I didn't want max date per ID, I wanted max date of only ID's 1,2,3. So if I added additional ID's like 4 & 5, then return only ID's 1,2,3,4,5. As you can see, there are mutliple ID's with different dates.
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Join & Write a Comment

Suggested Solutions

If you find yourself in this situation “I have used SELECT DISTINCT but I’m getting duplicates” then I'm sorry to say you are using the wrong SQL technique as it only does one thing which is: produces whole rows that are unique. If the results you a…
PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now