SQL选择两列组合的最高行

时间:2018-06-22 02:06:24

标签: mysql sql groupwise-maximum

我需要有关MySQL 5.5查询的帮助

在按location_id,count_number,try_number对行进行排序之后,我尝试仅选择2列组合(tan,location_id)中的1行。所以基本上我想有一个查询,该查询仅返回下图中的黄色行。 tan / location_id组合中该组中“ count_number”和“ try_number”最高的记录只有1条记录。

{{0}}

这是我目前拥有的查询。

$ ./bin/rand_10x10
  ,  i  i  0  +  h  >  3  O  ^
  }  j  c  p  y  l  q  >  z  X
  '  F  9  $  O  /  >  /  ,  }
  j  K  W  b  A  r  c  n  Z  m
  q  y  g  1  >  &  9  h  Y  k
  <  @  K  *  '  v  -  O  3  |
  l  l  :  ?  ;  1  c  =  +  <
  k  ;  6  u  p  }  -  e  E  m
  ,  f  %  d  C  \  J  w  :  [
  {  n  x  N  a  $  *  g  l  Y

2 个答案:

答案 0 :(得分:1)

我认为这可以满足您的要求

select iir.*
from inventario_inventoryregistry iir
where (count_number, try_number) = (select iir2.count_number, iir2.try_number
                                    from inventario_inventoryregistry iir2
                                    where iir2.tan = iir.tan and iir2.location_id = iir.location_id
                                    order by iir2.count_number desc, iir2.try_number desc
                                    limit 1
                                   );

答案 1 :(得分:0)

select tan, quantity, count_number, try_number, location_id
from
(select tan, quantity, count_number, try_number, location_id, row_number() over (partition by location_id, tan_id order by location_id desc, count_number desc, try_number desc) rw_nm
from inventario_inventoryregistry
where tan = '53-100554-01')
where rw_nm = 1;