BrunoLM
BrunoLM

Reputation: 100312

Select a specific column based on another column's value

I have a table like this

ID | Type | Val0 | Val1
1  |  0   |  A   | NULL
2  |  1   | NULL |  B

I need to select Val0 when the type is 0, and Val1 when the type is 1, and ValN when type is N...

How can I do that?

Upvotes: 20

Views: 76157

Answers (4)

cypheon
cypheon

Reputation: 1023

For low values of N, you can do it ad-hoc using the CASE statement, like CASE Type WHEN 0 THEN Val0 WHEN 1 THEN Val1 END. If your N is bigger, you should probably normalize your database (i.e. put ID => ValN mappings in a different table).

Upvotes: 2

Mchl
Mchl

Reputation: 62359

See CASE statement http://msdn.microsoft.com/en-us/library/ms181765.aspx

Upvotes: 1

OMG Ponies
OMG Ponies

Reputation: 332521

The way I read this, you need to use UNION:

SELECT a.val0
  FROM TABLE a
 WHERE a.type = 0
UNION ALL
SELECT a.val1
  FROM TABLE a
 WHERE a.type = 1
UNION ALL ...

UNION ALL doesn't remove duplicates, and is faster than UNION (because it removes duplicates).

Doing this dynamically is possible.

Upvotes: 3

dcp
dcp

Reputation: 55424

SELECT CASE
          WHEN Type = 0 THEN Val0
          WHEN Type = 1 Then Val1
          .
          .
          WHEN Type = N Then ValN
       END 
  FROM tbl

Upvotes: 29

Related Questions