Search code examples
sqlwindow-functionsazure-data-lakedelta-lake

How to write SQL query to read most recent timestamps (using window function)?


I have a table in my database that has rows inserted without updating old ones. That leads to having records with same ID but diffrent timestamps. How to write SQL query that uses window function to read rows with distinct IDs and most recent timestamps?


Solution

  • with base as (
    select *, row_number() over(partition by id order by timestamp desc) as rn from table
    )
    select * except(rn) from base
    where rn = 1