get the last insert entered sql

0

I have a database sql server 2012, where I have a table that contains a datetime field, and what I need is to get the last insert that was made, I have the following table and I hope you can help me

----------------------------------------------------------------------
|cod_reporte|nombre_ruta |email   |tipo        |descripcion |fecha    |
----------------------------------------------------------------------
| int       | varchar    |varchar |varchar     |varchar     |datetime |
-----------------------------------------------------------------------

What I need exactly is to get the last insert, specifying a route

example: route 1 = ..... .....

route 2 = ..... ....

I hope you can help me

    
asked by zhet 09.12.2016 в 23:00
source

3 answers

2

What I understand is that, for a particular route, you want to return the record with the most recent date. If this is what you want, you can use TOP 1 combined with ORDER BY for column fecha .

select top 1 *
  from tabla
 where nombre_ruta = 'valor_ruta'
 order by fecha desc

Here I leave you other options that you can use also using subqueries, or window function row_number() . But the option with TOP 1 is the simplest:

select *
  from tabla t
 where t.nombre_ruta = 'valor_ruta'
   and t.fecha = (select max(t2.fecha)
                    from tabla t2
                   where t2.nombre_ruta = t.nombre_ruta)

select t.*
  from (select t.*,
               row_number() over (order by t.fecha desc) as rn
          from tabla t
         where t.nombre_ruta = 'valor_ruta') t
 where t.rn = 1
    
answered by 09.12.2016 / 23:14
source
1

You can get it with

SELECT @@IDENTITY

This will bring you the last Id inserted

    
answered by 09.12.2016 в 23:05
0

Try something like this:

SELECT TOP 1 FROM TU_TABLA WHERE NOMBRE_RUTA="RUTA1" ORDER BY FECHA DESC

With this query you get a record TOP 1 of TU_TABLA where the RUBBER NAME is equal to the name of the route you need which is ordered by the DATE of signing down, from highest to lowest.

    
answered by 09.12.2016 в 23:20