执行特定类型的嵌套SELECT

时间:2016-06-04 18:11:49

标签: sql sql-server select nested

有一个“员工”表:

|  Name  |  Income  |  Job_Title  |
+--------+----------+-------------+
|  Adam  |   1000   |     ABC     |
|  Walt  |   1200   |     ABC     |
|  Kate  |   2000   |     XYZ     |
|  Abel  |   2500   |     XYZ     |
|  Judy  |   1300   |     ABC     |
|  Jess  |   2400   |     XYZ     |
|   ...  |    ...   |     ...     |

我想为每个人选择:人NameJob_Title,以及具有相同Income的人的最小和最大Job_Title,实现这一目标:

|  Name  |  Min     |   Max    | Job_Title  |
+--------+----------+----------+------------+
|  Adam  |   1000   |   1300   |    ABC     |
|  Walt  |   1000   |   1300   |    ABC     |
|  Kate  |   2000   |   2500   |    XYZ     |
|  Abel  |   2000   |   2500   |    XYZ     |
|  Judy  |   1000   |   1300   |    ABC     |
|  Jess  |   2000   |   2500   |    XYZ     |
|   ...  |    ...   |    ...   |    ...     |

(我可以找到/找出其他类型的嵌套SELECT的解决方案,但是这里......我很难过。)

1 个答案:

答案 0 :(得分:2)

获得您正在寻找的结果的一种方法是使用相关的子查询,如下所示:

select 
    name,
    (select min(income) from employees where Job_Title = e.Job_Title) as min,
    (select max(income) from employees where Job_Title = e.Job_Title) as max,
    Job_Title
from employees e

或者您可以使用公用表表达式来获取每个作业标题的最小/最大值并加入其中,如下所示:

with min_max as (
    select min(income) as min, max(income) as max, Job_Title 
    from Employees 
    group by Job_Title
)

select name, min, max, e.Job_Title
from Employees e 
join min_max mm on e.Job_Title = mm.Job_Title