获得组的最后一个

时间:2018-07-31 23:44:25

标签: mysql sql subquery aggregate-functions

我在mySQL中有一张表,该表跟踪某些基准的变化。看起来像这样:

id | person_id | datum        | value   | changed_on | 
=======================================================
1  | 1         | 'first_name' | 'Jane'  | 2018-06-12 | 
-------------------------------------------------------
2  | 1         | 'last_name'  | 'Smith' | 2018-06-12 | 
-------------------------------------------------------
3  | 1         | 'age'        | '29'    | 2018-06-12 | 
-------------------------------------------------------
4  | 1         | 'is_married' | '0'     | 2018-06-12 | 
-------------------------------------------------------
5  | 1         | 'is_married' | '1'     | 2018-07-28 | 
-------------------------------------------------------
6  | 1         | 'last_name'  | 'Blow'  | 2018-07-28 | 
-------------------------------------------------------
(repeat for other person_ids, etc.)
(ignore the fact that 29, 0 and 1 are technically text which is not optimal, I know)

我正在尝试获取每个datum的最后一个person_id。可以换位,但不一定要换位。我进行了一些研究,并came across one method(通过changed_on获取最新行。对我来说是

select *
from changes
where id in (
  select max(id)
  from changes
  group by person_id, datum
);

它确实可以工作,但是在id上是匹配的,而我想在changed_on上匹配(因为最新的更改可能不是最新的id)。我正在考虑做类似的事情:

select *
from changes
where id in (
  select id, max(changed_on)
  from changes
  group by person_id, datum
); /* somehow need the id of the max change */

但是显然,在这种情况下,您不能返回多列。我需要以某种方式获取从id返回的行中的max(changed_on)

1 个答案:

答案 0 :(得分:2)

我认为您的目标是:

select c.*
from changes c
where (person_id, datum, changed_on) in (
          (select c2.person_id, c2.datum, max(c2.changed_on)
           from changes c2
           group by c2.person_id, c2.datum
          );