我有一个查询,要求每个指定的ID每天最多提取一个条目。尽管已指定最大值,但查询每天仍返回多个值。我需要一些帮助来进行调整,这样我每天只能获得一个条目。该图显示了所返回数据的片段。
SELECT a.*
FROM turtle_derby AS a
INNER JOIN (SELECT turtle_id, DATE(`date`) AS day_date, MAX(`date`) AS maxdate
FROM turtle_derby
GROUP BY turtle_id, day_date) AS groupedtt
ON a.turtle_id = groupedtt.turtle_id
AND a.turtle_id = '175846'
AND a.`date` = groupedtt.maxdate
AND a.`date` > '2018-07-26'
ORDER BY `a`.`date`
答案 0 :(得分:0)
您的数据在一天中的同一时间具有多个行。如果该时间是一天中的最后时间,您将获得所有这些。您最多需要获取两列date
和loc_id
。参见SQL : Using GROUP BY and MAX on multiple columns
SELECT a.*
FROM turtle_derby AS a
INNER JOIN (
SELECT t2.turtle_id, MAX(t2.loc_id) AS max_id
FROM (
SELECT turtle_id, MAX(date) AS maxdate
FROM turtle_derby AS
GROUP BY turtle_id, DATE(date)
) AS t1
INNER JOIN turtle_derby AS t2
ON t1.turtle_id = t2.turtle_id AND t1.maxdate = t2.date
GROUP BY t1.turtle_id, t1.maxdate
) AS groupedtt
ON a.turtle_id = groupedtt.turtle_id
AND a.loc_id = groupedtt.maxloc
WHERE a.turtle_id = '175846'
AND a.`date` > '2018-07-26'
ORDER BY `a`.`date`