我遇到了SQL查询问题。 这是我的购买表:
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
我想为每封电子邮件选择最近的待定购买,因此我期待的结果是:
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
我有什么想法可以达到这个目的?
提前谢谢。
答案 0 :(得分:1)
您可以使用子查询执行此操作:
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;
这假定“最近的”是具有最大id
的那个。