1

I'm fairly new at SQL and have run into an issue that has me stumped. It's easier to just explain what I'm trying to do. I have a table that has a column t.number that contains either a 4, a 6 or something uninteresting to me. It corresponds with a a text field, t.text. Here's the pseudo code of what I want to do:

if (t.number == 4)
   t.text as ImAFour
else if (t.number == 6)
   t.text as ImASix

Everything I try to write ends up with double entries or overwriting. Any ideas?

midhunhk
  • 5,560
  • 7
  • 52
  • 83
KJ3
  • 5,168
  • 4
  • 33
  • 53
  • See the following post on the SQL CASE statement: http://stackoverflow.com/questions/4622/sql-case-statement-syntax – Garett Oct 23 '12 at 04:54

1 Answers1

2

You could try something like:

SELECT
    CASE t.number WHEN 4 THEN t.text ELSE '' END AS ImAFour,
    CASE t.number WHEN 6 THEN t.text ELSE '' END as ImASix,
    ....
FROM table t

The exact syntax will depend on your RDBMS, which was not tagged in the original question.

Ryan
  • 26,884
  • 9
  • 56
  • 83
  • Excellent that looks good, now again excuse my lack of experience, but can I just embed this select statement into my main select statement? I didn't mention but there are some other fields being pulled as well, but I've tried a version of that and it led to duplicates. Would I do: SELECT t.1, t.2, SELECT 'Your Code'? – KJ3 Oct 23 '12 at 04:55
  • Something like `SELECT field1, field2, ... CASE t.number WHEN 4 THEN t.text ELSE '' END AS ImAFour, CASE t.number WHEN 6 THEN t.text ELSE '' END as ImASix ... FROM table t ...` Each case statement becomes a seperate column/field in the query result set. – Ryan Oct 23 '12 at 13:20