也许这个问题是重复的,但我找不到我的任务的答案。我有下表的数据:
我需要选择具有唯一oid
的数据,并为每个oid选择最大日期。我有这些查询,但它们的工作不正确:
SELECT `oid`, `pvalue`, `date`
FROM `report`
WHERE `deviceid` = 'MRA-1011'
AND `date` <= '2012-01-20 00:00:00'
GROUP BY oid
HAVING `date` = MAX(`date`)
ORDER BY `date` DESC;
SELECT `oid`, `pvalue`
FROM `report`
WHERE `deviceid` = 'MRA-1011'
AND `date` <= '2012-01-20 00:00:00'
GROUP BY oid
ORDER BY `date` DESC;
我想得到这个结果:
答案 0 :(得分:3)
您需要使用以下行的子选择:
SELECT oid, pvalue FROM report
JOIN (SELECT oid, MAX(date) AS maxDate FROM report r WHERE `deviceid` = 'MRA-1011'
AND `date` <= '2012-01-20 00:00:00' GROUP BY oid) AS foo
ON foo.oid=r.oid AND foo.maxDate = report.date;
如果report.date不是唯一的,您可能希望在外部查询
中对其进行分组答案 1 :(得分:1)
试试这个::
SELECT `oid`, `pvalue`, `date`, MAX(`date`)
FROM `report`
WHERE `deviceid` = 'MRA-1011'
AND `date` <= '2012-01-20 00:00:00'
GROUP BY oid
HAVING `date` = MAX(`date`)
ORDER BY `date` DESC;
答案 2 :(得分:0)
SELECT `oid`, `pvalue`
FROM `report` AS `r1`
WHERE `deviceid` = 'MRA-1011'
AND `date` <= '2012-01-20 00:00:00'
AND `date` = ( SELECT MAX(`date`)
FROM `report` AS `r2`
WHERE `r1`.`oid` = `r2`.`oid`
)
;
答案 3 :(得分:-1)
为了得到这个结果,你必须
ORDER BY `date` ASC:
SELECT `oid`, `pvalue`
FROM `report`
WHERE `deviceid` = 'MRA-1011'
AND `date` <= '2012-01-20 00:00:00'
GROUP BY oid
HAVING `date` = MAX(`date`)
ORDER BY `date` ASC;