Skip to content

Instantly share code, notes, and snippets.

@julik
Created June 4, 2023 10:23
Show Gist options
  • Save julik/4f7137c3099e6cef673f76552c5ec835 to your computer and use it in GitHub Desktop.
Save julik/4f7137c3099e6cef673f76552c5ec835 to your computer and use it in GitHub Desktop.
Versioned table with grouping by updated_at
CREATE TABLE localities (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
source_updated_at TIMESTAMP,
name TEXT
);
INSERT INTO localities (name, source_updated_at) VALUES
('London', '2023-04-01'),
('London', '2023-03-15'),
('Paris', '2023-02-11'),
('Canberra', '2022-10-05');
WITH most_recent_ids AS (
SELECT DISTINCT(FIRST_VALUE(id) OVER (PARTITION BY name ORDER BY source_updated_at DESC)) AS id FROM localities
) SELECT * FROM localities INNER JOIN most_recent_ids ON most_recent_ids.id = localities.id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment