Solved

QUERY SEARCHING CLOSEST DATE

Posted on 2006-11-01
5
287 Views
Last Modified: 2008-03-06
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.
0
Comment
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
  • Learn & ask questions
5 Comments
 
LVL 28

Expert Comment

by:imran_fast
ID: 17849305
select  max(date)  date from yourtable where date <= getdate()
0
 
LVL 28

Expert Comment

by:imran_fast
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

by:dduser
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

by:
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

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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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.

728 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