MA_1023 MA_1023 - 2 months ago 7
SQL Question

SQL: Create new column with values that isn't in either columns

I basically have this table where 22 appears either in A or B:

A | B
---| ---
22 | 0
32 | 22
45 | 22
22 | 5


And I want to create a new column from this table that only has the value from the row that isn't 22 e.g.

C
-
0
32
45
5


How do I do this?

edit: The table above comes from this statement

SELECT A,B FROM table
WHERE (A = '22' OR B = '22')

Answer

You can use a case expression to generate this output:

SELECT CASE a WHEN 22 THEN b ELSE a END AS c
FROM   mytable 
WHERE  22 IN (a, b)
Comments