GotaloveCode
GotaloveCode

Reputation: 1034

Select statement with multiple rows from condition on values in single column

I have the table below.Using salary as condition I want to get multiple rows. Below is current table call it employee.

    empid     name         salary
-----------------------------------
1   A1        alex        20000
2   B2        ben         4500
3   C1        carl        14000

compare the salary to certain fixed values, and every time the salary is larger than the fixed value, show a record in output.My attempt condition case is close to this:

   incometype= case When salary<6000 then 101 When salary Between 6000 And 18000 Then
   102 Else 103 End

Desired ouput would be:

     empid     name   salary  incometype
------------------------------------------
1   A1        alex    20000    101
2   A1        alex    20000    102
3   A!        alex    20000    103
4   B2        ben     4500     101
5   C1        carl    14000    101
6   C1        carl    14000    102

I have tried using union but union will give me 3 rows for each record even when value meets 1st condition.

Upvotes: 1

Views: 3777

Answers (3)

shree.pat18
shree.pat18

Reputation: 21757

Your question is unclear, because your logic implies that you should only have 3 output rows for 3 input rows. Your output however implies that you want to compare the salary to certain fixed values, and every time the salary is larger than the fixed value, show a record in output.

If the former is the case, Minh's query is all you need. In the latter case, you can do something like this:

select e.*, m.incometype
from employee e
left join 
( 
 select 0 as threshold, 101 as incometype
 union
 select 5999 as threshold, 102 as incometype
 union
 select 17999 as threshold, 103 as incometype
) m
on e.salary > m.threshold
order by e.empid

If you want to add a calculate column i.e. one with values calculated using columns in this query, you can simply add it as a column in the select clause, like so:

select e.*, 
m.incometype, 
case 
when <first condition> then <business logic here>
....
else <handle default case>
end as yourcomputedcolumn
from
...

Upvotes: 4

anonxen
anonxen

Reputation: 824

Not very clear on the requirement, however the following worked for me:

Select 
    EmpId,Name,Sal,101 IncomeType
from Emp
Union all
Select 
    EmpId,Name,Sal,102
from Emp
Where Sal > 6000
union all
Select 
    EmpId,Name,Sal,103
from Emp
Where Sal > 18000;

Upvotes: 1

MinhD
MinhD

Reputation: 1810

This returns 3 rows and enough for your need:

  SELECT empid, name, salary, 
    case When salary<6000 then 101 
         When salary Between 6000 And 18000 Then 102 
         Else 103 End as incometype
    FROM employee;

Upvotes: 1

Related Questions