Choosing the maximum order number in SQL

I have a table that records the sequence of actions with a field that records the order of the sequence:

user    data    sequence
1       foo     0
1       bar     1
1       baz     2
2       foo     0
3       bar     0
3       foo     1

Selecting the first item for each user is simple enough with the sequence WHERE = '0', but is there a way to select the last item for each user in SQL?

As a result, I should look like this:

user    data    sequence
1       baz     2
2       foo     0
3       foo     1

I use MySQL if there are any special implementation tricks.

+3
source share
2 answers

This sql will return the record with the highest sequence value for each user:

select a.user, a.data, a.sequence
from table as a
    inner join (
        select user, max(sequence) as 'last'
        from table 
        group by user) as b
    on a.user = b.user and 
       a.sequence = b.last
+5
source
select top 1 
       user
       ,data
       ,sequence
 from table
order
   by sequence
0
source

Source: https://habr.com/ru/post/1697932/


All Articles