在mysql中获取具有最大列值的行

时间:2013-04-12 06:45:29

标签: mysql sql greatest-n-per-group

我一直在努力解决这个问题。我曾尝试过所有的方法,比如左外连接,分组依据甚至是子查询,但都无法成功。 这是我的询问。

select star_ident,transition_ident,fix_ident,sequence_num,route_type
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU';  

从上面的结果集中,我需要提取给定transition_ident和star_ident具有最大sequence_num的那些行。 这是我的查询。

select star_ident,transition_ident,fix_ident,max(sequence_num)
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU'
group by transition_ident,star_ident;

但是上面的查询产生了错误的结果。我甚至尝试过加入。

select yt1.star_ident,yt1.transition_ident,yt1.fix_ident
from corept.std_star_leg yt1
left outer join corept.std_star_leg yt2
on (yt1.star_ident = yt2.star_ident and yt1.transition_ident=yt2.transition_ident and      yt1.sequence_num < yt2.sequence_num)
where yt1.airport_ident='KMMU' and yt1.data_supplier='J'
and yt2.airport_ident='KMMU' and yt2.data_supplier='J' and yt2.star_ident is null;

但我最终得到了零行。为我提供了一种有效的方法。我需要为13K条目运行此查询。谢谢。

3 个答案:

答案 0 :(得分:2)

您的选择中有非聚合列,而不属于分组依据。

这 的 MYSQL DOCS

MySQL extends the use of `GROUP BY` so that the select list can refer to nonaggregated
columns not named in the GROUP BY clause. You can use this feature to get better
performance by avoiding unnecessary column sorting and grouping. However, this is 
useful primarily when all values in each nonaggregated column not named in the 
GROUP BY are the same for each group. The server is free to choose any value from 
each group, so unless they are the same, the values chosen are indeterminate.

因此,要获得正确的结果,请按

添加组中的所有选择列

修改

select b.* 
from 
corept.std_star_leg b
inner join
(select star_ident,transition_ident,max(sequence_num) as seq
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU'
group by star_ident,transition_ident) a
on b.star_ident = a.star_ident and a.transition_ident = b.transition_ident and
b.sequence_num = a.seq;  

希望它有所帮助......

答案 1 :(得分:1)

试试这个:

SELECT *
FROM
  (SELECT *
   FROM table1
   ORDER BY seqno DESC) tmp
GROUP BY `star_ident`,
         `trans`

以下是sqlfiddle

答案 2 :(得分:0)

通过start_ident删除组

select star_ident,transition_ident,fix_ident,max(sequence_num)
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU'
group by transition_ident