tags:

views:

494

answers:

2

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

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 easy enough with WHERE sequence = '0' but is there a way to select the last item for each user in SQL?

The result I am after should look like this:

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

I'm using MySQL if there are any implementation specific tricksters answering.

+3  A: 

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
Keith
Hmm, I'd have expected "inner join (select user, max(sequence) as 'last' from table group by user) as b on a.user = b.user". Different interpretations of the question, I guess.
ephemient
epheminent is technically correct (the best kind of correct).
Colonel Sponsz
Ah, you're right, thanks. He's grouped by user and only shown the last data.
Keith
Now corrected, grouped by user
Keith
In translating the meta variables into my data I had ended up with the right result anyway.
Colonel Sponsz
A: 

You can't do this with:

select   user,
         data,
         max(sequence)
from     table
group by user,
         data

?

David Aldridge
No - that returns each line of the table.
Colonel Sponsz
ah right. i'll try again ...
David Aldridge