Picking last value of each ID according to highest end year

Asked

Viewed 87 times

0

I have the following query:

select f.id_user as user, f.id_tempo, t.ano_inicial, t.ano_final 
from fato as f inner join tempo as t 
where f.id_tempo = t.id_tempo;

Which returns me the following table:

inserir a descrição da imagem aqui

What should I use in query to returns only one record of each user taking into account the largest ano_final and, if the final year is equal to 0, take into consideration the greater ano_inicial?

1 answer

1


whereas the ano_inicial is stored as whole:

select f.id_user as user, f.id_tempo, t.ano_inicial, t.ano_final 
from fato as f inner join tempo as t
where f.id_tempo = t.id_tempo 
  and t.ano_inicial = (select MAX(t1.ano_inicial) 
                       fato as f1 inner join tempo as t1
                       where f1.id_tempo = t1.id_tempo and f.id_user = f1.id_user);

edited

whereas there may be more than one occurrence of ano_inicial (returning more than one record, as commented), you limit the return:

select temp_table.id_user as user, temp_table.id_tempo, temp_table.ano_inicial, temp_table.ano_final 
from(
    select f.id_user as user, f.id_tempo, t.ano_inicial, t.ano_final 
    from fato as f inner join tempo as t
    where f.id_tempo = t.id_tempo 
      and t.ano_inicial = (select MAX(t1.ano_inicial) 
                           fato as f1 inner join tempo as t1
                           where f1.id_tempo = t1.id_tempo and f.id_user = f1.id_user);
) as temp_table
ORDER BY temp_table.id_tempo DESC 
LIMIT 1
  • When the id_user has in the case two records with the same value of ano_inicial it shows twice. in case I have 1 record only of each id_user i will need in case have a second verifier or can give a distinct?

  • @Doug, I edited the answer; I hope you fix it ;)

  • Gave error here but to trying to fix... Error Code: 1248. Every derived table must have its Own alias

  • ops.. lacked this, was bad. I’ll change again, but it’s bullshit

  • If I leave with the limit 1 it only returns 1 result

  • I didn’t test, but if you put the distinct, resolve? if not, we think of a where

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.