我有一张桌子,我们称之为桌子:
表(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>]

你能给我的任何指示我都非常感激。

最佳答案

这样就可以了

    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

10-01 07:15
查看更多