How to take out the last time SQL



  • A table

    id  Date_time   Log
    1   01.10.2021 15:30    Действие 1
    1   01.10.2021 15:35    Действие 2
    2   02.10.2021 10:00    Действие 1
    2   02.10.2021 12:00    Действие 2
    

    For each id, the last log, that is, the exit should be:

    id  Date_time   Log
    1   01.10.2021 15:35    Действие 2
    2   02.10.2021 12:00    Действие 2
    

    Zalil http://sqlfiddle.com/#!18/16a42/1 :



  • Use CTE and final function https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-ver15 :

    with tab as (
       select 
          id, Date_time, Log, 
          row_number() over(partition by id order by Date_time desc) as rn
       from table_name
    )
    select 
        id, Date_time, Log 
    from tab 
    where rn = 1
    

    http://sqlfiddle.com/#!18/c7836/1



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2