4

Maybe this question is duplicate, but I can not find an answer for my task. I have the next table with following data:

full table data

I need to select data with unique oid and with max date for each oid. I have these queries, but they work incorrectly:

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;

I want to get this result:

correct result

2
  • please add the result of these queries along with what u want from it..\ Commented Jan 9, 2012 at 9:28
  • @sashi-kant, see correct my question! Commented Jan 9, 2012 at 16:04

4 Answers 4

3

You need to use a subselect along the lines of:

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;

if report.date isn't unique you might want to group by it in the outer query

Sign up to request clarification or add additional context in comments.

1 Comment

There is a small error here. You cannot have r.oid outside the parenthesis where you define report r.
1

Try this ::

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;

1 Comment

This is not working for me as date is not dependent on the group by
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`
               )
;

Comments

-1

In order to have that result, you have to

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.