1

This is the data I have in my table. What I want is maximum sequence number for each order number.

Order No seq    Sta
--------------------
32100     1     rd
32100     3     rd
23600     1     rd
23600     6     rd

I want to get the following result without using cursor.

Output:

Order No seq  Sta
-----------------
32100     3   rd
23600     6   rd
3
  • 1
    Please edit your question to to add a tag for the database engine you're using (MySQL, Postgres, SQL Server, DB2, Oracle, ...) Commented May 6, 2018 at 4:54
  • Which database engine are you using? Commented May 6, 2018 at 4:54
  • Is Sta unique per Order No? Commented May 6, 2018 at 5:34

5 Answers 5

3

If you want entire records you could use ROW_NUMBER:

SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY Order ORDER BY No_Seq DESC) AS rn
      FROM tab) s
WHERE rn = 1;

DBFiddle Demo

Please do not use keywords like Order and spaces in column names.

Sign up to request clarification or add additional context in comments.

Comments

2

The most simple solution is using group by with max.

Give this a try:

select [Order No], max(seq), Sta
from myTable
group by [Order No]

2 Comments

This won't work on most RDBMSes . Sta has no agg function and it isn't in group by.
@Gowdam . . . It is sad that you accepted an answer that is not standard SQL, works in few databases, and promotes bad programming practices.
0

Just use group by order no and order by sequence desc and you will get your record.

Comments

0

If you are using Oracle Database then you can use ROW_NUMBER() analytical function to achieve this result

Try the below query:

select 
    * 
from
    (select 
         ROW_NUMBER() OVER (PARTITION BY order_no ORDER BY seq DESC) as "ROW_NUM", 
         order_no, seq, sta
     from 
         Order_Details) temp 
where 
    temp.row_num = 1 ;

Demo

Comments

0

The following is probably the most efficient solution in most databases (with the right index):

select t.*
from t
where t.seq = (select max(t2.seq) from t t2 where t2.orderno = t.orderno);

You can also do this with group by:

select orderno, max(seq), sta
from t
group by orderno, sta;

Note that all columns referenced in the select are either group by keys or arguments to aggregation functions. This is proper SQL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.