MySQL:从组中选择最后一个,但是有条件

时间:2012-10-10 15:25:49

标签: mysql sql select group-by

我有下表:

name     created_for created_on            status
jen      2012-05-27  2012-02-15 12:14:09    Y
joe      2012-10-01  2012-02-15 12:22:09    Y
bob      2012-10-01  2012-02-15 12:47:09    N
jim      2012-10-01  2012-02-24 12:47:09    N
jim      2012-10-01  2012-02-29 12:47:09    Y
sam      2012-10-01  2012-03-11 12:47:09    N
sam      2012-10-01  2012-03-15 12:47:09    C
sam      2012-10-01  2012-03-22 12:47:09    Y
tom      2012-10-01  2012-04-10 12:47:09    N
tom      2012-10-01  2012-04-11 12:47:09    N

我要返回的是名称的最后一行,created_on为每个创建日期为2012-10-01的人,但只有最后一个条目的状态为N.所以对于上表,我想回来:

name     created_on
bob      2012-02-15 12:47:09
tom      2012-04-11 12:47:09

状态条件是什么让我失望。我似乎无法弄清楚在哪里放置“where status ='N'”以获得正确的结果。

2 个答案:

答案 0 :(得分:2)

试试这个:

 SELECT t1.*
 FROM
 (
    SELECT name, MAX(created_on) MaxDate
    FROM YourTableName
    GROUP BY name
  ) t1 INNER JOIN YourTableName t2  on t1.name    = t2.name 
                                   AND t1.MaxDate = t2.created_on
 WHERE t2.created_for = '2012-10-01'
   AND t2.status = 'N'

答案 1 :(得分:2)

select t.*
from MyTable t
inner join (
    select name, max(created_on) max_created_on
    from MyTable
    where created_for = '2012-10-01'
    group by name
) tm on t.name = tm.name and t.created_on = tm.max_created_on
where t.status = 'N'

SQL Fiddle Example