0

I'm having trouble with a SQL query. This is my purchase table:

id       email                status       date
1        user1@server.com     confirmed    2014-10-01
2        user1@server.com     confirmed    2014-10-02
3        user2@server.com     pending      2014-10-02
4        user3@server.com     pending      2014-10-02
5        user1@server.com     pending      2014-10-03
6        user3@server.com     pending      2014-10-03
7        user1@server.com     pending      2014-10-04
8        user2@server.com     pending      2014-10-04
9        user2@server.com     pending      2014-10-05

I want to select the most recent pending purchase for each email, so the result I'm expecting is:

id      email                 status       date
6       user3@server.com      pending      2014-10-03
7       user1@server.com      pending      2014-10-04
9       user2@server.com      pending      2014-10-05

Any ideas how I can achieve this?
Thanks in advance.

Gerardo
  • 159
  • 1
  • 12

1 Answers1

2

You can do this with a subquery:

select p.*
from purchase p join
     (select email, max(id) as maxid
      from purchase
      where status = 'pending'
      group by email
     ) pmax
     on p.id = pmax.maxid;

This assumes that "most recent" is the one with the largest id.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786