How to filter records by date using SQL

Asked

Viewed 380 times

1

I am using SQL Server and need to query in a table the most recent price record as the date. Of all the records, I need him to bring me only 1 and with the current date. How do I do this?

inserir a descrição da imagem aqui

  • Is your column varchar? The result you expect is the date 12/03/2018?

  • Try something like this man: <b>select top 1 vr_preco from table Where dt_data = (select max(dt_data) from table)</b>. Note: I am considering that the field dt_data is date.

  • What is the version of SQL Server?

  • Version 2017....

2 answers

3

The figure shows that there are several lines for the same product.

The solution varies according to the version of SQL Server. Considering getting the latest information from a single product, we can have:

-- código #2
with Produto_ord as (
    SELECT ID_PRODUTOEMPRESA, DT_DATA, VR_PRECO,
           seq= row_number() over (order by DT_DATA desc)
      from tabela
      where ID_PRODUTOEMPRESA = ___
)
SELECT ID_PRODUTOEMPRESA, DT_DATA, VR_PRECO
  from Produto_ord
  where seq = 1;
  • Thank you @José Diz

2


It’ll be something like this you’re looking for?

SELECT      TOP 1 *
FROM        Tabela
ORDER BY    DT_DATA DESC
  • Thanks for the contribution @João Martins :)

  • You are welcome, always at your beck and call! If the answer was helpful, please give a UP :)

Browser other questions tagged

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