0

Let's say that I have a column weather (of a string type), all it values in fact are limited, for example, we can suppose, it only have five values with AAA, BBB, CCC, DDD, EEE.

Since I want to do some machine learning algorithms, I want to change the column type to INT, and at the same time, change its values into numbers 1, 2, 3, 4, 5 (corresponding to the existing values AAA, BBB, CCC, DDD, EEE).

How to write the T-SQL code ?

2
  • Which dbms are you using?!? Don't tag products not involved...
    – jarlh
    Dec 8, 2015 at 11:53
  • @jarlh sorry, I have deleted the unrelated labels. Dec 8, 2015 at 12:06

3 Answers 3

3

1. Do ALTER TABLE to add a new column new_weather_col integer.

2. Do an UPDATE to set new_weather_col's values:

update tablename
set new_weather_col = case weather when 'AAA' then 1
                                   when 'BBB' then 2
                                   when 'CCC' then 3
                                   when 'DDD' then 4
                                   when 'EEE' then 5
                      end;

3. ALTER TABLE to drop the old weather column.

4. ALTER TABLE again, this time to rename new_weather_col to weather.

(Edit: Perhaps I should add step 0 - make sure you have your table backup-ed before proceeding.)

2
  • Don't forget to DROP COLUMN weather before renaming.
    – Kobi
    Dec 8, 2015 at 13:02
  • OK, that solved my problem, thank you very much @jarlh Dec 8, 2015 at 13:42
0

Create another table with two columns: an int and a string. Populate the new table with your 5 strings and 5 unique integers. Join the two tables together by the string. Viola, you have integers.

0

If you have to write an SQL query for this which returns integers instead of string, you can do this in a case statement since you have fixed set of values.

select 1, case when weather = 'AAA' then 1 
                 when weather = 'BBB' then 2 
                 when weather = 'CCC' then 3
when weather = 'DDD' then 4
when weather = 'EEE' then 5 

            end 
from DUAL;  

I have used pl sql here. You can also do this in MySQL. The query snippet is just to give you an example. This will not run on the sql client.

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.