The problem is to fill missing values in a table. In pandas, one can use forward (or backward) filling to do so as shown below:
$> import pandas as pd
$> df = pd.DataFrame({'x': [None, 1, None, None, 2, None, 3, None]})
$> df['y'] = df['x'].fillna(method='ffill')
$> df
x y
0 NaN NaN
1 1 1
2 NaN 1
3 NaN 1
4 2 2
5 NaN 2
6 3 3
7 NaN 3
Is there a way to do that in SQL and more precisely in PostGres? I guess window functions could help but i couldn't figure out how.
In PostGres, it would be like:
sandbox=# SELECT x, ??
FROM
(SELECT NULL AS x
UNION ALL SELECT 1 AS x
UNION ALL SELECT NULL AS x
UNION ALL SELECT NULL AS x
UNION ALL SELECT 2 AS x
UNION ALL SELECT NULL AS x
UNION ALL SELECT 3 AS x
UNION ALL SELECT NULL AS x) a;
x
---
1
2
3
(8 rows)
lag
window function here - you will get previous x, nut not next to previous. In other words you want some kind of RECURSIVE LAG here, to repeat not previous value, but previous defined value – Shan