postgresql - How do I efficiently select the previous non-null value? -
i have table in postgres looks this:
# select * p; id | value ----+------- 1 | 100 2 | 3 | 4 | 5 | 6 | 7 | 8 | 200 9 | (9 rows)
and i'd query make this:
# select * p; id | value | new_value ----+-------+---------- 1 | 100 | 2 | | 100 3 | | 100 4 | | 100 5 | | 100 6 | | 100 7 | | 100 8 | 200 | 100 9 | | 200 (9 rows)
i can subquery in select, in real data have 20k or more rows , gets quite slow.
is possible in window function? i'd love use lag(), doesn't seem support ignore nulls option.
select id, value, lag(value, 1) on (order id) new_value p; id | value | new_value ----+-------+----------- 1 | 100 | 2 | | 100 3 | | 4 | | 5 | | 6 | | 7 | | 8 | 200 | 9 | | 200 (9 rows)
i found this answer sql server works in postgres. having never done before, thought technique quite clever. basically, creates custom partition windowing function using case statement inside of nested query increments sum when value not null , leaves alone otherwise. allows 1 delineate every null section same number previous non-null value. here's query:
select id, value, value_partition, first_value(value) on (partition value_partition order id) ( select id, value, sum(case when value null 0 else 1 end) on (order id) value_partition p order id asc ) q
and results:
id | value | value_partition | first_value ----+-------+-----------------+------------- 1 | 100 | 1 | 100 2 | | 1 | 100 3 | | 1 | 100 4 | | 1 | 100 5 | | 1 | 100 6 | | 1 | 100 7 | | 1 | 100 8 | 200 | 2 | 200 9 | | 2 | 200 (9 rows)
Comments
Post a Comment