Solved

# QUERY SEARCHING CLOSEST DATE

Posted on 2006-11-01
287 Views
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.

0
Question by:bruno_boccara
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 28

Expert Comment

ID: 17849305
select  max(date)  date from yourtable where date <= getdate()
0

LVL 28

Expert Comment

ID: 17849315

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]
0

LVL 9

Expert Comment

ID: 17849319
Select SKU,Min(DateDiff(day,YourDate,GetDate())) from YourTable where DateDiff(day,YourDate,GetDate()) >= 0
Group by SKU

Regards,

dduser
0

LVL 8

Accepted Solution

KelvinY earned 500 total points
ID: 17849329
Hi bruno_boccara,

Try

SELECT * FROM SKUTable WHERE SKU = 'abc' AND [DATE] = (SELECT MAX(DATE) FROM SKUTable WHERE SKU = 'abc' AND [DATE] <= GETDATE())

Regards
Kelvin
0

LVL 29

Expert Comment

ID: 17849343
select top 1 * from dbo.TESTDATE where DT < getdate()
order by DT desc
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
I have a large data set and a SSIS package. How can I load this file in multi threading?
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
###### Suggested Courses
Course of the Month7 days, 22 hours left to enroll