Cartman23
Cartman23

Reputation: 3

Carry forward the last non null value

I have a simple table like this:

Api_No14    Prod_Date   Oil_cf
42317448360000  2023-07-27  639.2337
42317448360000  2023-07-28  864.22
42317448360000  2023-07-29  NULL
42317448360000  2023-07-30  622.4919
42317448360000  2023-07-31  769.45
42317448360000  2023-08-01  1202.66
42317448360000  2023-08-02  1211.95
42317448360000  2023-08-03  1201.61
42317448360000  2023-08-04  732.73
42317448360000  2023-08-05  NULL
42317448360000  2023-08-06  678.8731
42317448360000  2023-08-07  NULL
42317448360000  2023-08-08  NULL
42317448360000  2023-08-09  1062.05
42317448360000  2023-08-10  876.3149

What I want is a new column that fills in the NULL data with non-null last value.

Api_No14    Prod_Date   oil oil_cf
a   7/27/2023   639 639
a   7/28/2023   864 864
a   7/29/2023       864
a   7/30/2023   622 622
a   7/31/2023   769 769
a   8/1/2023    1203    1203
a   8/2/2023    1212    1212
a   8/3/2023    1202    1202
a   8/4/2023    733 733
a   8/5/2023        733
a   8/6/2023    679 679
a   8/7/2023        679
a   8/8/2023        679
a   8/9/2023    1062    1062
a   8/10/2023   876 876

This is what I have tried so far:

WITH CTE AS 
(
    SELECT 
        API_NO14,
        Prod_Date,
        oil,
        MAX(oil) OVER (PARTITION BY API_NO14 
                       ORDER BY Prod_Date 
                       ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Oil_cf
    FROM 
        BASE_WELL_TEST_RATES
)
SELECT 
    Api_No14,
    Prod_Date,
    oil,
    Oil_cf
FROM 
    CTE

Upvotes: 0

Views: 39

Answers (0)

Related Questions