从两个值中获取最大值

时间:2019-04-27 17:33:38

标签: mysql sql mysql-workbench

我有一张桌子,它列出了每个站立位置骑手的骑行次数。我需要为每个骑行最多的骑手找到一个支架。

我的第一个结果是这样的格式:1

我需要这样的最终结果:2

我当前正在使用此查询,但是我知道可以用更好的方式来完成。任何建议都会有所帮助。

select c.rider_id, c.end_stand, b.max_rides
from
    (select rider_id, max(rides) as max_rides
    from
        (select rider_id, end_stand, count(id) as rides
        from ride where end_stand is not null
        group by 1,2) a
    group by 1
    order by 2 desc, 1) b
join
    (select rider_id, end_stand, count(id) as rides
    from ride where end_stand is not null
    group by 1,2) c
on c.rider_id = b.rider_id and c.rides = b.max_rides
order by 3 desc, 2,1

1 个答案:

答案 0 :(得分:1)

在使用窗口函数之前,一种方法是having子句中的相关子查询:

select rider_id, end_stand, count(*) as rides
from ride r
where end_stand is not null
group by rider_id, end_stand
having count(*) = (select count(*)
                   from ride r2
                   where r2.end_stand is not null and
                         r2.rider_id = r.rider_id
                   group by r2.rider_id, r2.end_stand
                   order by count(*) desc
                   limit 1
                  );

使用窗口功能,这当然要简单得多:

select *
from (select rider_id, end_stand, count(*) as rides
             rank() over (partition by rider_id order by count(*) desc) as seqnum
      from ride r
      where end_stand is not null
      group by rider_id, end_stand
     ) r
where seqnum = 1;

如果存在最大联系,则这两个都将返回重复项。如果只需要一行,那么第二个版本很容易修复:使用row_number()而不是rank()