Select most recent record from a given table - Postgresql

Asked

Viewed 8,478 times

0

I need to select the most recent record of my Estoque case the column data be different, I managed as follows to bring the oldest when the dates are different:

SELECT codigosuprimento, numeroserie, max(data)
FROM public.estoque where usado = '1' and numeroserie = '1201607048733' 
group by codigosuprimento, numeroserie;

But when the column data is the same I want him to bring all the records that the dates are the same, for example:

inserir a descrição da imagem aqui

I’d bring you both lines since the dates are the same, but when it is so:

inserir a descrição da imagem aqui

Would bring the date 2017-08-18 for being the most current.

1 answer

5


A solution can be a subselect with MAX

SELECT codigosuprimento, numeroserie, data
FROM public.estoque p1----faz uma primeira instancia da tabela 
where usado = '1' 
and numeroserie = '1201607048733' 
-- este subselect procura a maior data da mesma chave do registro
and data = (SELECT max(data)
            --faz uma segunda instancia da tabela 
            --renomeia o "alaias" para diferenciar
            FROM public.estoque p2
            where p2.usado       = p1.usado
            and   p2.numeroserie = p1.numeroserie)
  • It worked :) Could you just explain to me how your select? Once I release already mark as correct the answer

  • Just a question, I tried to execute this command without the restriction of a set serial number and kept loading and returning something after some time processing, in the matter of processing you would know something that consumes less who knows?

  • @Rovannlinhalis Has about 10,000 records more or less, the question of index in the date table as well as so index?

  • 1

    rotate the following command: CREATE INDEX estoque_data_idx ON public.estoque
 USING btree (data DESC); it will index the column to speed up the search. See the return time of the query in both cases and put the result there

  • @Rovannlinhalis after creating the index the response time was faster even, took a little longer but less than before, thank you

  • Just a question regarding this, in case I want to delete the data that have lower dates instead of just bringing the most current ones how could I do this?

  • @R.Santos there you have to see, you will need this record yet ? is useless ? erases. But thinking about it, maybe the right thing was to update the date and not delete one record and insert another with the same data. I didn’t understand the purpose of a stock table with this data, but ok.

  • Without the serious number restriction one falls almost certainly in a "full table scan".

Show 4 more comments

Browser other questions tagged

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