我目前有一个表,其中包含任何给定ID每天具有多个条目的数据。
我需要选择每天的最大日期,以免选择数百条记录。
我现在正在使用这个查询,但它只返回数据库中每个 id 的一个最大日期周期。
SELECT a.*
FROM turtle_locations a
INNER JOIN
(SELECT turtle_id, MAX(date) AS maxdate
FROM turtle_locations
GROUP BY turtle_id) groupedtt
ON a.turtle_id = groupedtt.turtle_id
AND a.date = groupedtt.maxdate
我想要的是,如果一只特定的在一天内说了 10 个条目,只返回当天的最新条目。
表结构非常简单: turtle_id、日期、纬度、经度
随着时间的推移,每只都有多个记录,每天有多个条目。 例如,查看其中一只海龟的以下数据
https://pastebin.com/jpQB2VKW
- 在子选择查询(派生表(中,还需要使用
Date()
函数按日期分组。这将为您提供每天的最大日期值和 id。
请尝试以下操作:
SELECT a.*
FROM turtle_locations AS a
INNER JOIN
(SELECT turtle_id,
DATE(`date`) AS day_date,
MAX(`date`) AS maxdate
FROM turtle_locations
GROUP BY turtle_id, day_date) AS groupedtt
ON a.turtle_id = groupedtt.turtle_id
AND a.`date` = groupedtt.maxdate
DB小提琴演示
http://sqlfiddle.com/#!9/861ab1/1
SELECT a.*
FROM turtle_locations a
LEFT JOIN turtle_locations b
ON a.turtle_id = b.turtle_id
AND a.date < b.date
WHERE b.turtle_id IS NULL