提问者:小点点

mysql按相同重复日期时间查询组


我有一个疑问。我有一个表,其中有些记录重复日期时间。我必须把最后一个从日期时间重复的地方拿来。示例:

它应该返回ID3、4和7

你能帮我吗?谢谢!


共2个答案

匿名用户

我认为您可以为此使用lead()。根据你的问题,它将是:

select t.*
from (select t.*, 
             lead(datetime) over (order by id) as next_datetime
      from t
     ) t
where next_datetime is null or next_datetime <> datetime;

根据您的示例数据,存在某种未指定的阈值。那么,类似这样的事情:

select t.*
from (select t.*, 
             lead(datetime) over (order by id) as next_datetime
      from t
     ) t
where next_datetime is null or
      next_datetime < datetime + interval 11 second;

注意:这假设datetime值与id值一起增加,这是一个合理的假设,给出了问题中的数据。

匿名用户

获取相同日期时间中每个日期时间的最后id:

SELECT timestamp, max(id)
FROM table
GROUP BY timestamp;

获取同一日期时间中每一行的完整行:

SELECT DISTINCT
  timestamp,
  FIRST_VALUE(id) OVER (PARTITION BY timestamp ORDER BY id DESC),
  FIRST_VALUE(value) OVER (PARTITION BY timestamp ORDER BY id DESC)
FROM table;