1st Row in Group By vs. Last Row

后端 未结 5 770
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 10:23

Wondering how to return the 1st row in a MySQL group by vs. the last row. Returning a series of dates, but need the first one displayed.

select * from calendar w         


        
相关标签:
5条回答
  • 2021-01-21 10:58

    Sounds like you want to use ORDER BY instead of GROUP BY:

    select * from calendar where approved = 'pending' order by eventid asc limit 1;
    
    0 讨论(0)
  • 2021-01-21 10:58

    If you want to show the first AND the last element of a group-by statement, this was useful for me:

    SELECT min(date) AS minn, max(date) AS maxx 
    FROM table_name
    GROUP BY occasion
    

    Thanks for the question

    0 讨论(0)
  • 2021-01-21 10:58

    I have the solution. To select the last row in a group, use this

    select * from calendar 
    where approved = 'pending' 
    group by eventid 
    ORDER BY max(`date`) DESC; 
    

    or this to select the first row from a group...

    select * from calendar 
    where approved = 'pending' 
    group by eventid 
    ORDER BY min(`date`) DESC; 
    

    The DESC does not matter, it only sorts the entire filtered result by descending order, after a row from each group has been selected.

    0 讨论(0)
  • 2021-01-21 11:10

    Use the min function insead of max to return the first row in a group vs the last row.

    select min(date) from calendar ...
    

    If you want the entire row for each group, join the table with itself filtered for the min dates on each group:

    select c2.* from
        (select eventid, min(dt) dt from calendar
            where approved = 'pending' group by eventid) c1
    inner join calendar c2 on c1.eventid=c2.eventid and c1.dt=c2.dt
    group by eventid;
    

    Demo: http://www.sqlize.com/6lOr55p67c

    0 讨论(0)
  • 2021-01-21 11:15

    When you use GROUP BY like that, MySQL makes no guarantees about which row in each group you get. Indeed, theoretically it could even pick some of the columns from one row and some from another. The MySQL Reference Manual says:

    "MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. [...] You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

    What you want to do instead is something like this:

    SELECT
      calendar.*
    FROM
      calendar
      NATURAL JOIN (
        SELECT
          eventid, MIN(date) AS date
        FROM
          calendar
        GROUP BY eventid
      ) AS foo
    
    0 讨论(0)
提交回复
热议问题