SQL CASE

Write SQL CASE statement.

The CASE statement used for conditions and returns a value when the first condition is met like 

IF THE ELSE IF STATEMENT

Example


Table: Employee                             
+----+-------+--------+--------------+      
| Id | Name  | Salary | DepartmentId |      
+----+-------+--------+--------------+      
1  | Ram   | 85000  | 1            |      
2  | Henry | 80000  | 2            |      
3  | Sam   | 60000  | 2            |      
4  | Shyam | 60000  | 1            |
5  | Geeta | 90000  | 1            |
6  | Sheet | 90000  | 1            |
7  | Leela | 80000  | 1            |
8  | Geeta | 70000  | 1            |
+----+-------+--------+--------------+

Query: Defining the Employee GRADE based on SALARY



SELECT NAME,SALARY,
     (CASE WHEN(SALARY<50000THEN 'E GRADE'
     WHEN(SALARY>50000 AND SALARY<=60000THEN 'D GRADE'
     WHEN(SALARY>60000 AND SALARY<=70000THEN 'C GRADE' 
     WHEN(SALARY>70000 AND SALARY<=80000THEN 'B GRADE'
     WHEN(SALARY>80000THEN 'A GRADE' ENDAS EMP_GRADE
FROM EMPLOYEE

Result : 

+-------+--------+--------------+      
Name  | Salary | EMP_GRADE    |      
+-------+--------+--------------+      
| Ram   | 85000  | A GRADE      |      
| Henry | 80000  | B GRADE      |      
| Sam   | 60000  | D GRADE      |      
| Shyam | 60000  | D GRADE      |
| Geeta | 90000  | A GRADE      |
| Sheet | 90000  | A GRADE      |
| Leela | 80000  | B GRADE      |
| Geeta | 70000  | C GRADE      |
+-------+--------+--------------+

Related post

  1. Write an SQL query to reformat the table such that there are a department id column and a revenue column for each month using case



No comments:

Post a Comment