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

我的未来我决定 提交于 2019-12-24 14:34:07

问题


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.


回答1:


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
...



回答2:


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;



回答3:


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;


来源:https://stackoverflow.com/questions/24300423/select-statement-with-multiple-rows-from-condition-on-values-in-single-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!