Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with SQL Select 1

Status
Not open for further replies.

pwomack

Technical User
Apr 16, 2005
121
US
I have the following data in a table.

select OrderNo, OptKey, JobDate
from OptimizerJob
order by OrderNo, JobDate

OrderNo OptKey JobDate
123456 1414388210 2009-04-07 14:18:40.030
123456 306771073 2009-04-07 14:19:05.280
1234567 1184659209 2009-04-07 14:19:28.500
1234567 1661234550 2009-04-07 14:19:59.373
12345678 621885380 2009-04-07 14:22:23.520
123456789 2102027589 2009-04-07 14:23:01.960
123456789 1232245987 2009-04-07 14:23:28.663
123456789 1035518668 2009-04-07 14:42:24.287

I want to write a Select statement that returns only the order number and optkey for the latest job date.

So, I want this returned:

OrderNo OptKey
123456 306771073
1234567 1661234550
12345678 621885380
123456789 1035518668

Can someone help?
 
All of the records in your example have the same job date. Wouldn't you return all of them?

How would the code know what the job date is? A parameter? Another table?
 
Code:
SELECT a.*
FROM OptimizerJob a

INNER JOIN

(SELECT OrderNo, MAX(JobDate) AS MaxDate
FROM
OptimizerJob
GROUP BY OrderNo) b

ON a.OrderNo = b.OrderNo AND a.JobDate = b.MaxDate
 
Thanks, RiverGuy.

I'm an admirer of your knowledge.
 
Or for SQL Server 2005 and up you can do it more "modern" way

select * from (select * from OptimizerJob, row_number() over (partition by OrderNo order by JobDate DESC) as Rn) Ranked where Rn = 1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top