Question

Using Oracle11g:

If the column is null, I want to exclude the arithmetic on the column.

In this case, how can I get lag_diff for seqno=1 to be null?

   with detail_records as (
    select 1 seqno, 10 set_a  from dual union all
    select 2 seqno, 10 set_a  from dual union all
    select 3 seqno, 20 set_a  from dual union all
    select 4 seqno, 30 set_a  from dual )
  select  seqno,
          set_a,
          lag_val,
    case (lag_val - set_a)
    when 0 then 'AAA'
    else  'BBB'
    end  as lag_diff
 from ( select seqno, 
        set_a, 
        lag(set_a,1) over (order by seqno) as lag_val       
  from detail_records)
order by seqno

Desired Results

  SEQNO  SET_A LAG_VAL LAG_DIFF
  ----------------------------
  1       10  <NULL>   <null>
  2       10   10       AAA
  3       20   10       BBB
  4       30   20       BBB
Was it helpful?

Solution

change your case to the following:

 with detail_records as (
    select 1 seqno, 10 set_a  from dual union all
    select 2 seqno, 10 set_a  from dual union all
    select 3 seqno, 20 set_a  from dual union all
    select 4 seqno, 30 set_a  from dual )
  select  seqno,
          set_a,
          lag_val,
    case 
    when (lag_val - set_a) is null then null
    when (lag_val - set_a) = 0 then 'AAA'
    else  'BBB'
    end  as lag_diff
 from ( select seqno, 
        set_a, 
        lag(set_a,1) over (order by seqno) as lag_val       
  from detail_records)
order by seqno
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top