Created
October 9, 2022 11:57
-
-
Save Compro-Prasad/cd133bab889a065a0788d6dbb8cba475 to your computer and use it in GitHub Desktop.
Get most recent non null values from a table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE table1 ( | |
id BIGSERIAL, | |
main_id int not null, | |
created TIMESTAMP DEFAULT NOW(), | |
value1 VARCHAR, | |
value2 VARCHAR, | |
value3 VARCHAR, | |
); | |
INSERT INTO table1(main_id, value1) VALUES(1, 'a'); | |
INSERT INTO table1(main_id, value1, value2) VALUES(1, 'b', 'c'); | |
INSERT INTO table1(main_id, value1, value3) VALUES(2, 'd', 'e'); | |
INSERT INTO table1(main_id, value2) VALUES(1, 'f'); | |
CREATE VIEW table1_view AS | |
SELECT main_id, value1, value2, value3 | |
FROM ( | |
SELECT | |
main_id, | |
FIRST_VALUE(value1) OVER ( | |
PARTITION BY main_id | |
ORDER BY (created || value1) DESC NULLS LAST | |
) AS value1, | |
FIRST_VALUE(value2) OVER ( | |
PARTITION BY main_id | |
ORDER BY (created || value2) DESC NULLS LAST | |
) AS value2, | |
FIRST_VALUE(value3) OVER ( | |
PARTITION BY main_id | |
ORDER BY (created || value3) DESC NULLS LAST | |
) AS value3 | |
FROM table1 | |
) AS test1 | |
GROUP BY main_id, value1, value2, value3; | |
-- TODO: Create table and attach a trigger for better efficiency. Views are just macros. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment