返回带有MAX(日期)和GROUP BY id的sql查询行

时间:2017-05-16 06:17:21

标签: sql greatest-n-per-group

id      position      date
1          c          2012 01 22
2          b          2012 01 23
3          a          2012 01 22

如何通过id

获取MAX(日期)分组的记录行
NullPointerException

4 个答案:

答案 0 :(得分:1)

SELECT t.id, t.position, r.Maxdate
FROM (
      SELECT id, MAX(date) as Maxdate
      FROM Yourtable
      GROUP BY id
) r
INNER JOIN Yourtable t
ON t.id = r.id AND t.date = r.Maxdate

答案 1 :(得分:0)

select your_table.* from your_table  
inner join 
(select max(date) as maxdt, id from your_table  group by id) t
on your_table.id = t.id and your_table.date  = t.maxdt

答案 2 :(得分:0)

这通常使用窗口函数完成:

select id, position, "date"
from (
  select id, position, "date", max("date") over (partition by id) as max_date
  from the_table
) t
where "date" = max_date
order by id;

答案 3 :(得分:0)

我读了其他答案,但这也行。我不明白为什么需要第二次选择。

SELECT id, my_position, Max(my_date)
FROM test.test
GROUP BY id