I have a table with columns codigo
, data
and valor
. I would like to get, for each code, the value corresponding to the most recent date. In what ways can this be done? And if there is more than one, which is the most efficient. Example:
minha_tabela
codigo data valor
-------------------------------
1 2014-01-01 10
1 2014-01-02 20
2 2014-01-03 30
2 2014-01-04 40
2 2014-01-05 50
3 2014-01-06 60
Expected result:
codigo data valor
-------------------------------
1 2014-01-02 20
2 2014-01-05 50
3 2014-01-06 60
Getting the latest date is easy: just group by
with max
aggregation. The problem is getting the value for that date:
select t.codigo as codigo, max(t.data) as data, ??? as valor
from minha_tabela t
group by t.codigo;
I would like a solution that works in the "standard" SQL, without depending on the particular characteristics of any specific DBMS.