MYSQL在日期的多列中选择最大值

时间:2018-07-15 06:02:00

标签: mysql

假设我有一个名为“ bowlmark”的表,并且该表的摘要如下所示: (此表记录了每个投球手的保龄球标记)

这是示例表摘要:

bowler_id---record_date---round1mark---round2mark
101---2018-06-02---100---164
102---2018-06-02---102---120
101---2018-06-03---150---124
103---2018-06-03---200---122

我想在每个记录日中输出最高分并显示礼帽ID

对于上面的示例,我希望输出为:

date:2018-06-02, bowler_id:101, highestmark: 164 
date:2018-06-03, bowler_id:103, highestmark: 200 . 

如何编写此SQL查询?谢谢。

2 个答案:

答案 0 :(得分:1)

这有点丑陋,但是我可以这样:

SELECT b.bowler_id, a.* FROM (
  SELECT record_date, MAX(GREATEST(round1mark, round2mark)) AS greatest
  FROM bowlers
  GROUP BY record_date
) a
INNER JOIN bowlers b ON
    a.record_date = b.record_date AND
    a.greatest = GREATEST(b.round1mark, b.round2mark)

SQLFiddle此处:http://sqlfiddle.com/#!9/3718ec/17

答案 1 :(得分:0)

您可以在子查询上使用great和一个内部联接以获得最大舍入标记

  select   m.bowler_id, m.record_date
     , greatest(round, round2, round3, round4, round5, round6) highest_mark
  from bowlmark m 
  inner join (
    select record_date 
      , max(greatest(round, round2, round3, round4, round5, round6)) as max_round
    from bowlmark
    group by record_date 
  ) t on t.record_date = m.record_date 
        and greatest(round, round2, round3, round4, round5, round6) = t.max_round

无论如何,正确的数据库规范化可以帮助您避免此类问题