如何在SQL Server 2008中对此进行子查询?

时间:2012-08-20 06:01:58

标签: sql

在SINGLE SQL语句中计算豁免员工的最低工资和非豁免员工的平均工资。使用子查询将两个元素合并到查询中。它应该看起来像:

Min Exempt Salary   Average Non-Exempt Salary
47,000                           35,271

我知道如何将其分开,但无法按照上述说明如何做到这一点,这是我的判断。

SELECT jobs1.exempt_nonexempt_status,
       Min (employees.salary)AS Minimal_Exempt_Salary
FROM   employees
       LEFT JOIN jobs1
              ON employees.job_title = jobs1.job_title
WHERE  jobs1.exempt_nonexempt_status = 'Exempt'
GROUP  BY jobs1.exempt_nonexempt_status

SELECT jobs1.exempt_nonexempt_status,
       Avg (employees.salary)AS Average_Non_Exempt_Salary
FROM   employees
       LEFT JOIN jobs1
              ON employees.job_title = jobs1.job_title
WHERE  jobs1.exempt_nonexempt_status = 'Non-exempt'
GROUP  BY jobs1.exempt_nonexempt_status 

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT 
    MIN(CASE WHEN J.exempt_nonexempt_status = 'Exempt'
             THEN E.Salary
             END) AS Minimal_Exempt_Salary,

    SUM(CASE WHEN J.exempt_nonexempt_status = 'Non-exempt'
             THEN E.Salary
             END) AS Average_Non_Exempt_Salary

FROM Employees E
LEFT JOIN JOBS1 J ON J.job_title = E.job_title
WHERE J.exempt_nonexempt_status IN ('Exempt', 'Non-exempt')

答案 1 :(得分:1)

执行此操作的常规方法是:

select  j.exempt_nonexempt_status
,       avg(case when j.exempt_nonexempt_status='Non-exempt' then e.salary end) 
            as Average_Non_Exempt_Salary
,       min(case when j.exempt_nonexempt_status='Exempt' then e.salary end)
            as Minimal_Exempt_Salary
from    Employees e 
left join 
        jobs1 j
on      e.job_title = j.job_title
group by 
        j.exempt_nonexempt_status

但是这不使用子查询。另一种方法是将两个查询包装在外部选择中:

select  (
        select MIN (employees.salary)
        from Employees left join jobs1
        on employees.job_title = jobs1.job_title
        where jobs1.exempt_nonexempt_status='Exempt'
        group by jobs1.exempt_nonexempt_status
        ) as MinimalExemptSalary
,       (
        select avg (employees.salary)
        from Employees left join jobs1
        on employees.job_title = jobs1.job_title
        where jobs1.exempt_nonexempt_status='Non-exempt'
        group by jobs1.exempt_nonexempt_status
        ) as AverageNonExemptSalary