2

我有一个我们称之为 table: 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>]

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

4

3 回答 3

0

即使您的 maxend并不总是对应于 maxid并且如果有几个id具有相同的 maximal ,这也应该有效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小提琴

于 2013-07-11T23:54:38.210 回答
0

这应该做的工作

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

在这里演示

由于您的建议,请尝试此 编辑

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

在这里演示

于 2013-07-11T23:39:54.770 回答
0
select * from
(select id,pid,end from Table1 order by pid asc, end desc) abc
group by pid;

小提琴

于 2013-07-23T15:13:44.013 回答