如何检索列中的最后一个非零值

时间:2015-11-26 16:27:42

标签: oracle

所以这就是我所看到的

Column 1 Column 2 Column 3

103.46  15-10-02    150.60
381.67  15-10-02    150.60
741.31  15-10-03    0
14.21   15-10-03    0
35.37   15-10-05    0
11.24   15-10-12    19.23
13.77   15-10-13    0

我想在第3列中插入零以前的非零值

所以我会看到像

这样的东西
Column 1 Column 2 Column 3

103.46  15-10-02    150.60
381.67  15-10-02    150.60
741.31  15-10-03    150.60
14.21   15-10-03    150.60
35.37   15-10-05    150.60
11.24   15-10-12    19.23
13.77   15-10-13    19.23

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

LAST_VALUE()将满足您的需求:

with table1 as (select 103.46 col1, to_date('01/10/2015', 'dd/mm/yyyy') col2, 0 col3 from dual union all
                select 381.67 col1, to_date('02/10/2015', 'dd/mm/yyyy') col2, 150.60 col3 from dual union all
                select 741.31 col1, to_date('03/10/2015', 'dd/mm/yyyy') col2, 0 col3 from dual union all
                select 14.21 col1, to_date('03/10/2015', 'dd/mm/yyyy') col2, 0 col3 from dual union all
                select 35.37 col1, to_date('05/10/2015', 'dd/mm/yyyy') col2, 0 col3 from dual union all
                select 11.24 col1, to_date('12/10/2015', 'dd/mm/yyyy') col2, 19.23 col3 from dual union all
                select 13.77 col1, to_date('13/10/2015', 'dd/mm/yyyy') col2, 0 col3 from dual)
select col1,
       col2,
       nvl(last_value(decode(col3, 0, cast(null as number), col3)) ignore nulls over (order by col2, col3 desc), 0) col3
from   table1;

      COL1 COL2             COL3
---------- ---------- ----------
    103.46 01/10/2015          0
    381.67 02/10/2015      150.6
    741.31 03/10/2015      150.6
     14.21 03/10/2015      150.6
     35.37 05/10/2015      150.6
     11.24 12/10/2015      19.23
     13.77 13/10/2015      19.23

答案 1 :(得分:-1)

您是否考虑过使用CASE STATEMENT

CASE 
    WHEN Column1 <> 0 THEN Column1
    WHEN Column2 <> 0 THEN Column2
    ELSE Column3
END AS NewColumn3