Skip to content

Instantly share code, notes, and snippets.

@YarikST
Created October 10, 2019 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YarikST/d4a855aec023ebfe5752cc5abb89b6fb to your computer and use it in GitHub Desktop.
Save YarikST/d4a855aec023ebfe5752cc5abb89b6fb to your computer and use it in GitHub Desktop.
DROP TABLE IF EXISTS histories;
CREATE TEMP TABLE histories
as
select *
from (
VALUES
(1::int, 1::int, 'status_1'::VARCHAR),
(2::int, 1::int, 'status_1'::VARCHAR),
(3::int, 1::int, 'status_1'::VARCHAR),
(4::int, 2::int, 'status_2'::VARCHAR),
(5::int, 2::int, 'status_2'::VARCHAR),
(6::int, 3::int, 'status_3'::VARCHAR),
(7::int, 3::int, 'status_3'::VARCHAR),
(8::int, 3::int, 'status_3'::VARCHAR),
(9::int, 3::int, 'status_3'::VARCHAR),
(10::int, 4::int, 'status_4'::VARCHAR),
(11::int, 5::int, 'status_5'::VARCHAR),
(12::int, 5::int, 'status_5'::VARCHAR),
(13::int, 5::int, 'status_5'::VARCHAR),
(14::int, 5::int, 'status_5'::VARCHAR),
(15::int, 5::int, 'status_5'::VARCHAR),
(16::int, 5::int, 'status_5'::VARCHAR),
(17::int, 5::int, 'status_5'::VARCHAR)
) as t (id, user_id, status);
select t1.* from histories t1 left outer join histories t2 on t2.id > t1.id and t1.user_id = t2.user_id where t2.id isnull
-- condition max search
select t1.* from histories t1 left outer join (SELECT * from histories where created_at <= '2018-06-04 14:00:14.720713 UTC'::timestamp ) t2 on t2.id > t1.id and t1.user_id = t2.user_id where t2.id isnull and t1.created_at <= '2018-06-04 14:00:14.720713 UTC'::timestamp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment