Home > OS >  SQL, with if then else, move some value from a column to another
SQL, with if then else, move some value from a column to another

Time:06-27

in SQL Server,

how can I move value from a column to another with conditional (if then else) ? I'm explain with an example.

I have a table with

Article Desc. UM Value
Item1 Flower PC 5001
Item2 Paper PC 6001
Item2 Paper CT 6002
Item3 Pen CT 7001
Item4 Eraser PC 8001

I need to have

Article Desc. Value PC ValueCT
Item1 Flower 5001 NULL
Item2 Paper 6001 NULL
Item2 Paper NULL 6002
Item3 Pen NULL 7001
Item4 Eraser 8001 NULL

I thought to do a If then else

Something like that: if UM = 'PC' then begin instruction to move value to "Value PC" end else begin instruction to move value to "Value CT" end

But I don't know which instruction use to move only value that I need to move.

Can you help me ?

CodePudding user response:

This looks like you just need a simple case expression,

select Article, [Desc.],
    case when UM = 'PC' then Value end ValuePC,
    case when UM = 'CT' then Value end ValueCT
from t;
  • Related