Question

Oracle 11g My work so far on SQL Fiddle

I'm using lead() and lag() functions on varchar2 columns. Using the following rules, I'd like to generate the desired results.

  1. If lag_val is null then '('
  2. If lag_val is same as set_a then 'and'
  3. If lag_val != set_a then 'or'
  4. If lead_val is null then ')'

I get 'invalid number' when I use nvl() to convert null values so I can compare.

Desired Output

   SEQNO SET_A LAG_VAL  LEAD_VAL  MENU_ENTRY
   ------------------------------------------
   1      CAKE  <null>  CAKE      (
   2      CAKE  CAKE    BEER      AND
   3      BEER  CAKE    BRATS     OR
   4      BRATS BEER    <null>    )
Was it helpful?

Solution

Your problem is that you're using the "-" operator on strings, not with lead/lag. I think you want this:

select  seqno,
         set_a,
         lag_val,
         lead_val
    , case 
    when (lag_val ) is null then '('
    when (lead_val ) is null then ')'
    when (lag_val = set_a) then 'and'    
    else  'or'
    end  as menu_entry
from ( select seqno, 
        set_a, 
        lag(set_a,1) over (order by seqno) as lag_val,
--        lag(to_number,'XX') over (order by seqno) as lag_val,
        lead(set_a,1) over (order by seqno) as lead_val       
 from menu_items)
order by seqno
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top