分组依据和desc重复名称

时间:2016-10-10 20:09:43

标签: mysql sql

我需要帮助分组问题。我正在使用mysql来获取表的最后一行(红色行)。

这是示例数据的样子:

enter image description here

我尝试过的查询:

Select *,min(remain),max(Sequance) 
from ApplePen
Group by Name
Order by max(Sequance);

然后我得到的结果是:

enter image description here

我想要的结果是:

(将在此处显示。现在我们不知道。也许上面的箭头)

2 个答案:

答案 0 :(得分:1)

由于您在样本输出中使用的颜色不太确定,但我相信这是您可能需要的:

select
  a.max_id,
  a.name,
  b.use,
  a.max_remain,
  a.min_sequance,
  a.max_remain,
  a.max_sequance
from (
  select 
      name
    , max(id) as max_id
    , min(remain) as min_remain
    , max(sequance) as max_sequance
    , max(remain) as max_remain
    , min(sequance) as min_sequance
  from applepen
  group by name
  ) a
left join applepen b on 
  a.name = b.name and a.id = b.id

为每个MIN计算MAXname列值,然后返回max(id)use列。

答案 1 :(得分:0)

您可以使用元组和子选择

  select * from ApplePen
  where (remain, sequance) in  (select min(remain), max(sequance) from ApplePen)