I have two views in PostgreSQL. One to get the most recent total amounts of each organization. The other view is to get the second to last most recent total amounts of each organization and here is the problem: How to get the second to last MAX(date) in PostgreSQL? This is my code (note that 'date' is one of my columns, not the function):
CREATE VIEW vw_totaaldossiers AS
SELECT SUM(aantal) as totaal
FROM _dossier i1
WHERE date = (
SELECT MAX(date)
FROM _dossier i2
WHERE i2.instantie = i1.instantie
GROUP BY i2.instantie
);
CREATE VIEW v2_relatiefdossiers AS
SELECT SUM(aantal) as relatief
FROM _dossier i3
WHERE date = (
SELECT /* Here comes the second to last MAX(date) */
FROM _dossier i4
WHERE i4.instantie = i3.instantie
GROUP BY i4.instantie
);
Thanks for the help!