Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Finding difference between two dates

Author  Topic 

crugerenator
Posting Yak Master

126 Posts

Posted - 2008-09-08 : 11:42:41
I'm trying to write a select statement where i return only rows with the shortest amount of time between two dates.

For example:

select userID,
deliveryDate,
orderdDate

from Orders

where (Amount of time between orderDate and deliveryDate is
smallest)
and deliveryDate > GetDate()+2

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2008-09-08 : 13:12:25
Do you want just one row returned or perhaps one row per userID?

Are you using sql server 2005 (or greater)?

Be One with the Optimizer
TG
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2008-09-08 : 13:20:02
assuming 2005 and one row per userID - here's one way:

select userID,
deliveryDate,
orderdDate
from (
select userID,
deliveryDate,
orderdDate,
row_Number() over (partition by userID order by datediff(millisecond, orderDate, deliveryDate)) as rn
from Orders
where deliveryDate > GetDate()+2
) d
where d.rn = 1


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -