[英]SQL select max value in a group
I'm stuck on this for days now. 我已经坚持了好几天了。 I have 3 fields, tot_order, slsnum and ordernum. 我有3个字段,tot_order,slsnum和ordernum。 I need to get the max value in ordernum, which is a unique field and its total order number in the ordernum field. 我需要在ordernum中获得最大值,这是一个唯一字段,其总订单号在ordernum字段中。 The slsnum field is based on a date, so I could have a slsnum# 18443450 repeatedly per row. slsnum字段基于日期,因此我可以每行重复输入slsnum#18443450。
tot_order: 240, 100, 50 tot_order:240、100、50
ordernum: 23006343, 220110021, 180872124 订单号:23006343、220110021、180872124
I need the end result like this: tot_order: 240 slsnum: 18443450 ordernum: 23006343 我需要这样的最终结果: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)
. WHERE
子句中的子查询引用主查询中的slsnum
字段以获取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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.