0

I have a table with indicators of directions and based on that I need to derive a new column which tells whether its IN or Out

ORG_IN  ORG_OUT DEST_IN DEST_OUT    Direction
0   0   0   0   NULL
0   0   0   1   Out
0   0   1   0   In
0   1   0   0   Out
0   1   0   1   Out
0   1   1   0   NULL
1   0   0   0   In
1   0   0   1   NULL
1   0   1   0   In

This is the query where ill derived the direction http://sqlfiddle.com/#!4/a9f82/1

Do you think it will cover all cases in future for all the combinations. Right now I can see only above combinations. Any better way to write the sql.

1 Answer 1

0
select t.*, case ORG_IN + DEST_IN - ORG_OUT - DEST_OUT 
              when 2 then 'In'
              when 1 then 'In'
              when 0 then null
              when -1 then 'Out'
              when -2 then 'Out'
            end as Direction
from tablename t

I can't figure out any more valid combinations. However, I'd recommend a check constraint that makes sure no invalid combinations are entered:

check (ORG_IN + ORG_OUT < 2 and DEST_IN + DEST_OUT < 2)
1
  • Nothing wrong, more a matter of taste. (And perhaps readability.)
    – jarlh
    Commented Nov 21, 2017 at 8:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.