如何选择每组中包含最新日期的记录

时间:2013-07-11 23:29:18

标签: mysql ruby-on-rails-3 activerecord arel

我有一张桌子,我们称之为桌子: table(id:integer,pid:integer,end:datetime)

具有以下数据:

table:
id    pid   end
1     1     1
2     1     2
3     1     3
4     2     11
5     2     12
6     2     13
7     3     21
8     3     22
9     3     23
10    4     31
11    4     32
12    4     33

我需要做的是选择记录的ID,按pid分组,最高结束值。我的输出(作为ActiveRecord :: Relation)应该如下:

[#<Table id: 3, pid: 1, end: 3>,
 #<Table id: 6, pid: 2, end: 13>,
 #<Table id: 9, pid: 3, end: 23>,
 #<Table id: 12, pid: 4, end: 33>]

你能给我的任何方向都非常感谢。

3 个答案:

答案 0 :(得分:0)

这应该做的工作

    select `id` , `pid` , `end` from table1
    where `end` in (select max(`end`) from table1)

DEMO HERE

根据您的建议尝试修改

     select `id` , `pid` , `end` from 
    ( select max(id) id ,`pid` ,max(`end`) as `end` from table1 group by `pid`)t

DEMO HERE

答案 1 :(得分:0)

即使您的最高end并不总是与最大id对应,并且有多个id具有相同的最大end,这也应该有效。

SELECT t1.id, t1.pid, t1.end FROM Table1 t1
JOIN 
(SELECT pid AS 'pid2', MAX(end) AS 'end2' FROM Table1 GROUP BY pid) t2
ON t2.pid2=t1.pid AND t2.end2=t1.end
#GROUP BY t1.pid  #in case there are several records with same 'pid' and 'end' and you want to select any one of those

SQL Fiddle

答案 2 :(得分:0)

select * from
(select id,pid,end from Table1 order by pid asc, end desc) abc
group by pid;

fiddle