简体   繁体   中英

SQL select max value in a group

I'm stuck on this for days now. I have 3 fields, tot_order, slsnum and ordernum. I need to get the max value in ordernum, which is a unique field and its total order number in the ordernum field. The slsnum field is based on a date, so I could have a slsnum# 18443450 repeatedly per row.

tot_order: 240, 100, 50

ordernum: 23006343, 220110021, 180872124

I need the end result like this: tot_order: 240 slsnum: 18443450 ordernum: 23006343

You can use a correlated subquery for this:

SELECT tot_order, slsnum, ordernum
FROM table as t1
WHERE ordernum = (SELECT max(ordernum) FROM table as t2 WHERE t2.slsnum = t1.slsnum)

That subquery in the WHERE clause references the slsnum field in the main query to grab the max(ordernum) .

You can do this with the following query:

Select tot_order, slsnum, ordernum
from table as t
where ordernum>=ALL(
     Select ordernum from t
 )

Give this a whirl..

SELECT tot_order, slsnum, ordernum
FROM YourTable
WHERE OrderNum = (SELECT Max(OrderNum) FROM YourTable) 
SELECT *
from table_name
where ordernum = (
  select max(ordernum) from table 
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM