Link to home
Start Free TrialLog in
Avatar of bruno_boccara
bruno_boccaraFlag for France

asked on

QUERY SEARCHING CLOSEST DATE

Hi, I'm searching the best and simplest way to make the following query:

I've got some SkU with specific dates. you can find multiple row with same sku, but with different date.
I want the closest date from today (getdate), but not greater.

Sample.

ID      SKU      date
1        abc       01/01/2004
2        abc       01/01/2005
3        abc       01/01/2006
4        abc       01/01/2007

I want the row with ID 3, because the date is closest than date's row ID1 and ID 2.

ID 4's date is closest than ID 3's date but is greater than getdate so not good.

Thank you for your help.
Avatar of imran_fast
imran_fast

select  max(date)  date from yourtable where date <= getdate()

select A.* from yourtable A
inner join (
select  max(date)  [date] , sku  from yourtable  where date <= getdate() group by sku )B
on A.sku = B.sku and A.[date] = b.[date]
Select SKU,Min(DateDiff(day,YourDate,GetDate())) from YourTable where DateDiff(day,YourDate,GetDate()) >= 0
Group by SKU

Regards,

dduser
ASKER CERTIFIED SOLUTION
Avatar of KelvinY
KelvinY

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gautham Janardhan
select top 1 * from dbo.TESTDATE where DT < getdate()
order by DT desc