从单列中的值条件中选择具有多行的语句

时间:2014-06-19 06:48:37

标签: sql select conditional-statements

我有下表。使用薪水作为条件我想获得多行。 下面是当前的表呼叫员工。

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

将薪水与某些固定值进行比较,每当薪水大于固定值时,在输出中显示一条记录。我的尝试条件案例接近于此:

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

所需的输出将是:

     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

我尝试过使用union,但即使值满足第一个条件,union也会为每条记录提供3行。

3 个答案:

答案 0 :(得分:4)

您的问题不清楚,因为您的逻辑意味着您应该只有3个输入行的3个输出行。但是,您的输出意味着您要将薪水与某些固定值进行比较,并且每次薪水大于固定值时,都会在输出中显示记录。

如果是前者,那么Minh的查询就是您所需要的。在后一种情况下,你可以这样做:

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

如果要添加计算列,即使用此查询中的列计算值的计算列,您只需将其添加为select子句中的列,如下所示:

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

答案 1 :(得分:1)

这会返回3行,足以满足您的需求:

  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;

答案 2 :(得分:1)

对要求不是很清楚,但以下方法对我有用:

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;
相关问题