SQL case statement is like "if then else " in programming.
Below are some example (high level):
Syntax:
For a particular column:
Select column1, column2, .....,
case
when < condition > then result
or
when < condition1 > and < condition2 > then result
Else different_result --> Else is used if needed
End as result_columnName
from Table_Name
Example 1:
Select EmpID , EMP_NAME, SALARY,
Case
When salary >2000 then ‘No Bonus’
When salary >1000 and salary <2000 then ‘Bonus
$100’
When salary <1000 then ‘Bonus $ 200’
End as BONUS
From Table_Name;
Example 2:
Select LOCATION , DEPARTMENT, STATE,
Case
When STATE = ‘IL’ then ‘HEAD OFFICE’
When STATE = ‘TX’ then ‘WAREHOUSE’
ELSE ‘BRANCH OFFICE’
END AS OFFICE
FROM TABLE_NAME;
Example 3: Another way of writing case statement.
Select LOCATION , DEPARTMENT, STATE,
Case STATE
When ‘IL’ then ‘HEAD OFFICE’
When ‘TX’ then ‘WAREHOUSE’
ELSE ‘BRANCH OFFICE’
END AS OFFICE
FROM TABLE_NAME;
No comments:
Post a Comment