简体   繁体   English

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

[英]How do I subquery this in SQL Server 2008?

Calculate the minimum salary for exempt employees and the average salary for non-exempt employees in a SINGLE SQL statement. 在SINGLE SQL语句中计算免税员工的最低薪水和非免税员工的平均薪水。 Use subqueries to incorporate both elements in the query. 使用子查询将两个元素合并到查询中。 It should look something like: 它看起来应该像这样:

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

I know how to do it separate but cannot figure how to do it as it stated above , this is the statments I have. 我知道如何分开做,但是不能确定如何做,如上所述,这是我的发言。

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 

Try this: 尝试这个:

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')

A normal way to do this would be: 通常的方法是:

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

But that doesn't use subqueries. 但这不使用子查询。 Another way is to wrap your two queries in an outer select: 另一种方法是将两个查询包装在外部选择中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM