题解 | #考试分数(五)#

考试分数(五)

http://www.nowcoder.com/practice/b626ff9e2ad04789954c2132c74c0512

本题思路

  1. 找出各个分组内的排序
	SELECT
      g.id as id,
      g.score as score,
      CAST(
        if(
          @ pre_job = g.job,
          @ cur_rank: = @ cur_rank + 1,
          @ cur_rank: = 1
        ) AS SIGNED
      ) ranking,
      @ pre_job: = g.job as job
    FROM
      grade g,
      (
        SELECT
          @ cur_rank: = 0,
          @ pre_job: = NULL
      ) r
    ORDER BY
      g.job,
      g.score DESC
  1. 找出各个分组的中位数,我这里定义成了page_from以及page
	select
      job,
      IF(count(*) % 2 = 1, 1, 2) as page,
      ceil(count(*) / 2) as page_from
    from
      grade
    group by
      job
  1. 聚合1,2结果并排序
SELECT
  b.id as id,
  b.job as job,
  b.score as score,
  b.ranking as t_rank
FROM
  (
    select
      job,
      IF(count(*) % 2 = 1, 1, 2) as page,
      ceil(count(*) / 2) as page_from
    from
      grade
    group by
      job
  ) a
  left join (
    SELECT
      g.id as id,
      g.score as score,
      CAST(
        if(
          @ pre_job = g.job,
          @ cur_rank: = @ cur_rank + 1,
          @ cur_rank: = 1
        ) AS SIGNED
      ) ranking,
      @ pre_job: = g.job as job
    FROM
      grade g,
      (
        SELECT
          @ cur_rank: = 0,
          @ pre_job: = NULL
      ) r
    ORDER BY
      g.job,
      g.score DESC
  ) b on a.job = b.job
  and b.ranking >= a.page_from
  and b.ranking < (a.page_from + a.page)
order by
  b.id;
全部评论
看了其他同学的题解发现还能使用ROW_NUMBER()函数,不过MySQL 的ROW_NUMBER()函数是从8.0版开始引入的
点赞 回复 分享
发布于 2022-03-20 12:42

相关推荐

11-07 13:31
怀化学院 Java
勇敢牛牛不怕难:又疯一个
点赞 评论 收藏
分享
有工作后先养猫:太好了,是超时空战警,我们有救了😋
点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务