1

I have oracle database table 'mytable' with following data-

ID          ORDER    ACTION     CB        TV
35547225    CHANGE<  Add        TV       100788581
35355239    CHANGE<  Add        G76763164 014580531
35779535    CHANGE   Add        TVservi   038894810
35591230    CHANGE<  Add        G87178597   
35814001    CHANGE   Rem        TVservi   011733179
35418962    CHANGE<  Rem        TV        011733179

I want to get output in following format with additional column as 'CT'-

ID          ORDER   ACTION  CB          TV          CT
35547225    CHANGE  Add                 100788581   Only TV
35355239    CHANGE  Add     G76763164   014580531   Both
35779535    CHANGE  Add                 038894810   Only TV
35591230    CHANGE  Add     G87178597               Only CB
35814001    CHANGE  Remove              011733179   Only TV
35418962    CHANGE  Remove              011733179   Only TV

I want following changes in output -

  • In 'ORDER' column - if it is 'CHANGE<' in 'mytable' then it should be 'CHANGE' in output.

  • in 'ACTION' column - if it is 'Rem' in 'mytable' then it should be 'Remove' in output.

  • In 'CB' column - if it is starting with G and then 8 digit number then keep as it is otherwise make it NULL in output

  • Add one more column 'CT' in output by writing remark based on following condition-

    • If CB is NULL and TV is NOT NULL then 'Only TV'

    • If CB is NOT NULL and TV is NOT NULL then 'Both'

    • If CB is NOT NULL and TV is NULL then 'Only CB'

1
  • DECODE is your friend for all these things (or CASE). Commented Oct 4, 2018 at 15:14

1 Answer 1

3

You can use the CASE clause to compute the various column values according to arbitrary logic:

select
    id,
    case when "order" = 'CHANGE' then 'CHANGE'
         when "order" = 'CHANGE<' then 'CHANGE'
    end as "order",
    case when action = 'Rem' then 'Remove'
         else action
    end as action,
    case when regexp_like(cb, 'G[0-9]{8}') then cb
         else null
    end as cb,
    tv,
    case when cb is null and tc is not null then 'Only TV'
         when cb is not null and tv is not null then 'Both'
         when cb is not null and tv is null then 'Only CB'
    end as ct
  from my_table

Note that order is a reserved word that you don't normally use as a column name. If you want to use it, you need to enclose it in double quotes (").

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.