how to get distinct rows with max value

前端 未结 4 1721
萌比男神i
萌比男神i 2020-12-17 04:47

my apologies for asking what must be very simple to solve, but I just can\'t seem to wrap my mind around this.. I couldn\'t even come up with a really fitting title for my q

相关标签:
4条回答
  • 2020-12-17 05:29
    select * from (select * from answers order by votes desc) as temp group by authorId
    
    0 讨论(0)
  • 2020-12-17 05:42

    Great question, Dan.

    MySQL lacks the analytical functions to make this easy to solve. A similar question has been asked of Oracle and was solved using the OVER clause with the MAX function. This works on SQL Server too.

    You need to use subqueries to do it on MySQL. This works for me:

    SELECT
      id,
      authorId,
      answer,
      votes
    FROM answers AS firsts
    WHERE id = (
      SELECT
        MIN(id)
      FROM answers AS favorites
      WHERE
        votes = (
          SELECT MAX(votes)
          FROM answers AS author_max
          WHERE author_max.authorId = favorites.authorID
        ) AND
        favorites.authorId = firsts.authorId 
    )
    ORDER BY votes DESC;
    

    See my sqlfiddle for an executable example.

    0 讨论(0)
  • 2020-12-17 05:48

    You can use a sub-select:

    select min(a1.id), a1.authorid, a2.mxvotes
    from answers a1
    inner join
    (
      select authorid, max(votes) mxvotes
      from answers
      group by authorid
    ) a2
      on a1.authorid = a2.authorid
      and a1.votes = a2.mxvotes
    group by a1.authorid, a2.mxvotes
    order by mxvotes desc
    

    see SQL Fiddle with Demo

    0 讨论(0)
  • 2020-12-17 05:50
    SELECT id, authorId, answer, votes
    FROM (  SELECT id, authorId, answer, votes
            FROM answers
            ORDER BY votes DESC) AS h
    GROUP BY authorId
    

    This little neat trick is built basing on GROUP BY to retrieve the first row of each case. Usually this is by default ORDER BY id ASC, but through this sub query, the first row in each authorId with the highest votes.

    Note: As mentioned by Iain Elder, this solution doesn't work with ONLY_FULL_GROUP_BY active and only works in MySQL. This solution is to a certain extent unsupported due to lack of documentation confirming this behavior. It works well for me and has always worked well for me however.

    This method still works on the latest MySQL on sqlfiddle.

    0 讨论(0)
提交回复
热议问题