Skip to content

Instantly share code, notes, and snippets.

@jonasdw
Created August 6, 2019 07:13
Show Gist options
  • Save jonasdw/65db9be4dde7f9db02756fef37beddf3 to your computer and use it in GitHub Desktop.
Save jonasdw/65db9be4dde7f9db02756fef37beddf3 to your computer and use it in GitHub Desktop.
person | version | date | created_at | data
1 | 1 | 01/01/2019 | 05/08/2019 | null
2 | 1 | 01/01/2019 | 05/08/2019 | null
1 | 1 | 02/01/2019 | 05/08/2019 | null
2 | 1 | 02/01/2019 | 05/08/2019 | null
1 | 2 | 01/01/2019 | 06/08/2019 | "some data"
1 | 3 | 01/01/2019 | 06/08/2019 | "some altered data"
1 | 3 | 01/01/2019 | 05/08/2019 | "also altered data"
/*
DESIRED RESULT
I want to select the data for all different persons and dates at the highest versions and highest created at.
It is possible for the same person, data and version to co-exists (the created at will never be the same in this case)
*/
(person 1, date 01/01/2019, "some altered data")
(person 1, date 02/01/2019, null)
(person 2, date 01/01/2019, null)
(person 2, date 02/01/2019, null)
@jonasdw
Copy link
Author

jonasdw commented Aug 6, 2019

select dpr.person, dpr.date, dpr.data from table dpr
inner join (
select dpr1.person, dpr1.date, max(created_at) as mostrecent
from table dpr1
inner join
(SELECT
dpr.person, dpr.date, max(dpr.version) as maxversion
FROM
table dpr
GROUP BY
person, date) as dpr2
ON dpr1.person = dpr2.person AND dpr1.date = dpr2.date AND dpr1.version = dpr2.maxversion
group by dpr1.person, dpr1.date
) as dpr2
ON dpr.person = dpr2.person AND dpr.date = dpr2.date AND dpr.created_at = dpr2.mostrecent
ORDER BY dpr.person, dpr.date;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment