Profile

Friday, 8 July 2011

SQL: Convert data in multiple conditions using CASE WHEN..THEN

From this example above, the original table has a column 'Color' which store the color specification of the product line.

Let's assume now when developing a ETL, this column need to be convert to 'colorcode' to display the color description as number.
We could use CASE WHEN.. THEN in SQL to convert the table for reporting.
In this situation, using CASE WHEN..THEN is better than just IF..THEN because CASE WHEN could easily setup multiple conditions.
In this example we have to place a color code for black, silver, and red in our product table:

 
USE AdventureWorks2008
GO
SELECT Name,
CASE WHEN ([COLOR]='BLACK') THEN 1
WHEN ([COLOR]='SILVER') THEN 2
WHEN ([COLOR]='RED') THEN 3
ELSE 0 END AS COLORCODE
FROM
Production.Product

After we run the query, notice that the column 'colorcode' has converted color name into integer numbers:

No comments: