Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
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, orderdDatefrom Orderswhere (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 OptimizerTG
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, orderdDatefrom ( select userID, deliveryDate, orderdDate, row_Number() over (partition by userID order by datediff(millisecond, orderDate, deliveryDate)) as rn from Orders where deliveryDate > GetDate()+2 ) dwhere d.rn = 1