Nube1 Nu2 Nube1 Nu2 - 2 months ago 6
SQL Question

Sql group by and order by first date entered

I want to get the first datetime from the column datetime. The results is always the other way around. Using that query below, outputs the latest record. I want the opposite outputs of the latest record. How can I achieve the desired result?

name datetime
John August 23, 2015 03:50:01
John August 23, 2015 03:50:14
Jane August 23, 2015 04:51:11
Jane August 23, 2015 05:00:11


The desired result should be

name datetime
John August 23, 2015 03:50:01
Jane August 23, 2015 04:51:11


I'm using this query

SELECT * FROM person GROUP BY name

Answer

Here is one method:

select p.*
from person p
where p.datetime = (select max(p2.datetime) from person p2 where p2.name = p.name);

Note: if two rows have exactly the same datetime value, you will get both.

Comments