简体   繁体   中英

Calculate field based on previous calculated condition field

So I am working on a solution where that involves three columns "row number", "type", "factor". Based on this I would like to generate the column "factor_adj". The issue I am facing is that it depends on a previous row with a condition. I have been playing around with window function, but cannot seem to get the expected result. How can I achieve this??

The pseudo logic on this is as following:

IF "row number" == 1
    then 1
ELSE IF Previous Type == 'related' then
    Previous factor_adj*0.1
ELSE
    Previous factor_adj*0.2
END

Here is a snippet with EXPECTED result for "factor_adj"

+------------+---------+---------------+---------------+
| row number |  type   |    factor     |  factor_adj   |
+------------+---------+---------------+---------------+
|          1 | regular |             1 |             1 |
|          2 | regular |        0.6226 |           0.2 |
|          3 | regular |  0.4626319149 |       0.12452 |
|          4 | regular |        0.3492 | 0.09252638298 |
|          5 | regular |  0.2662688742 |       0.06984 |
|          6 | regular |  0.2038145695 | 0.05325377483 |
|          7 | regular |  0.1587655629 | 0.04076291391 |
|          8 | related |  0.1229311258 | 0.03175311258 |
|          9 | regular | 0.09119205297 |  0.1217018146 |
|         10 | regular | 0.06457218542 | 0.01823841059 |
+------------+---------+---------------+---------------+

For test and replication:

CREATE TABLE factor_test (
    row_number integer,
    "type" varchar(256),
    "factor" float

)

insert into factor_test (row_number, "type", factor)
values  (1, 'regular', 1),
(2, 'regular', 0.6226),
(3, 'regular', 0.4626319149),
(4, 'regular', 0.3492),
(5, 'regular', 0.2662688742),
(6, 'regular', 0.2038145695),
(7, 'regular', 0.1587655629),
(8, 'related', 0.1229311258),
(9, 'regular', 0.09119205297),
(10, 'regular', 0.06457218542);

I'll add this as an starter. It corresponds with your expected result down to the related row, can you elaborate on how the remaining rows are to be calculated?

select row_num, type, factor
     , case when row_num = 1 
              then 1
            when lag(type) over (order by row_num) = 'related' 
              then 0.1 * lag(factor) over (order by row_num)
            else 
                   0.2 * lag(factor) over (order by row_num)
       end as factor_adj
from factor_test

By declaring an explicit window it becomes a bit shorter:

select row_num, type, factor
     , case when row_num = 1 then 1
            when lag(type) over w = 'related' then 0.1 * lag(factor) over w
            else 0.2 * lag(factor) over w
       end as factor_adj
from factor_test
window w AS (order by row_num)

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM