Search code examples
teradataoperator-precedence

Populate column on PRECEDING calculation in Teradata


I have two fields – Date and OPR_DIST , I Need to compute OPR_MILEAGE

For OPR_MILEAGE – If Null(?) and Zero in OPR_DIST then ZERO for OPR_MILEAGE

If OPR_DIST is not zero (eg: 0.37) , I check the Prev. record (here its 0) hence OPR_MILAGE corresponding to 0.37 is 0

If OPR_DIST is not zero (eg: 0.46) , I check the Prev. record (here its 0.37, which is not zero) hence OPR_MILAGE corresponding to 0.46 is same as OPR_DIST which is 0.46

So at any point, if my preceding record is zero, My current values for OPR_MILEAGE is zero, else OPR_DIST. Version I am using is TD 13

DATE    OPR_DIST    OPR_MILEAGE
6/10/2016   ?       ?
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0.37    0
6/10/2016   0.46    0.46
6/10/2016   0.47    0.47
6/10/2016   0       0
6/10/2016   0.32    0
6/10/2016   0.37    0.37
6/10/2016   0.47    0.47
6/10/2016   0.56    0.56
6/10/2016   0.32    0.32
6/10/2016   0.26    0.26
6/10/2016   0       0
6/10/2016   0.3     0
6/10/2016   0       0
6/10/2016   0.36    0
6/10/2016   0.25    0.25
6/10/2016   0.25    0.25
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0       0
6/10/2016   0.46    0
6/10/2016   0.24    0.24
6/10/2016   0       0
6/10/2016   0.33    0
6/10/2016   0       0
6/10/2016   0       0

I am new to TD. Any light on this could help.


Solution

  • If there's a column to determine the order (probably a timestamp), you simply need to check the previous row's value:

    CASE WHEN MAX(OPR_DIST)
              OVER (ORDER BY ???    -- previous row 
                    ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) > 0
         THEN OPR_DIST
         ELSE 0
    END