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 Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Select statement 2

Status
Not open for further replies.

cs2009

Programmer
Joined
Aug 10, 2009
Messages
50
Location
US
Using SQL Server 2005.

I need help with a SQL Select statement. I have the following order numbers in a table and I want to select the lastest order number, which is the first 6 digits. The last 3 digits are the sequence numbers.

order_no
123456_00
123456_01
123456_02
987654_00
987654_01
385646_00

The result should return these order numbers:

order_no
123456_02
987654_01
385646_00
 
Code:
SELECT d.*
FROM

YourTable d

INNER JOIN

(SELECT OrdNo, MAX(Seq) AS MaxSeq
FROM

(SELECT a.*, LEFT(order_no, 6) AS OrdNo, RIGHT(order_no, 2) AS Seq
FROM YourTable) b

GROUP BY OrdNo) c

ON c.OrdNo + '_' + c.MaxSeq = d.order_no
 
You should consider separating the order number from the sequence number in to separate columns in your table. It's very easy to concatenate them together for display purposes. If you cannot do this, then....

Code:
Select	Max(order_no)
From	YourTable
Group By Left(order_no, 6)

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Nice and simple solution George !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top