我有一个我们称之为表的表: 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>]
非常感谢您能给我的任何指示。
最佳答案
这应该可以完成工作
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
关于mysql - 如何在每个组中选择具有最新日期的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605230/