如何简化这个子查询?

时间:2014-12-06 05:23:41

标签: mysql sql sql-server select subquery

我从http://www.programmerinterview.com/index.php/database-sql/derived-table-vs-subquery/看到了这个子查询,并且它有以下子查询作为示例,但是说它可以写得更简单。谁能告诉我怎么做?谢谢!

一个名为employee的表,其列为employee_name,last_name,employee_salary和employee_number。我们希望找到薪水高于平均水平的所有员工。

   select employee_name 
    from employee
    where employee_salary >
    (select avg(employee_salary)
            from employee)

5 个答案:

答案 0 :(得分:1)

您可以使用OVER子句计算average工资以及当前员工的工资是否大于它。不幸的是,window函数不能在where子句中使用,所以你也应该使用comman表表达式。

DECLARE @employee TABLE
(
     [employee_name] VARCHAR(12)
    ,[employee_salary] INT
)

INSERT INTO @employee ([employee_name], [employee_salary])
VALUES ('Empl1', 100)
      ,('Empl2', 200)
      ,('Empl3', 300)
      ,('Empl4', 400)
      ,('Empl5', 500)
      ,('Empl6', 600)
      ,('Empl7', 700)
      ,('Empl8', 800)

-- your query
 select employee_name 
    from @employee
    where employee_salary >
    (select avg(employee_salary)
            from @employee)

-- alternative query
;WITH DataSource AS
(
     select employee_name
           ,employee_salary - AVG(employee_salary) OVER () AS diff
     from @employee
 )
 SELECT employee_name
 FROM DataSource
 WHERE diff > 0

答案 1 :(得分:0)

试试这个:

SELECT employee_name 
FROM employee e 
INNER JOIN (SELECT AVG(employee_salary) salary FROM employee) e1 ON e.employee_salary > e1.salary;

SELECT employee_name 
FROM employee e 
WHERE EXISTS (SELECT 1 FROM employee e1 WHERE e.employee_salary > AVG(e1.employee_salary)); 

答案 2 :(得分:0)

我认为您的查询设计得很好。 使用JOIN效率较低,HAVING子句将在检索后过滤数据。然后,您将让所有员工过滤平均工资。

答案 3 :(得分:0)

希望这会有所帮助

--DECLARE A TABLE VARIABLE
DECLARE @Emp AS TABLE

(
     ID                 INT
    ,EMPLOYEE_NAME      VARCHAR(50)
    ,EMPLOYEE_SALARY    NUMERIC(18,2)

)
-- ADD SOME VALUES TO THE TABLE
INSERT INTO @Emp
VALUES (1,'DANNY',7000),(2,'JOHN',10000),(3,'DAVID',1000)

--AVERAGE SALARY IS 6000..

--USING COMMON TABLE EXPRESSIONS
    ; WITH CTE AS
     (
        SELECT 
            AVG(EMPLOYEE_SALARY)  AS AVGSALARY
        FROM @EMP       
    )
        SELECT 
            EMPLOYEE_NAME
        FROM 
            @Emp    EMPLOYEE    -- MY TABLE
        INNER JOIN
            CTE
        ON
            EMPLOYEE_SALARY>CTE.AVGSALARY

答案 4 :(得分:-1)

代表sql server 2012

    select iif(((employee_salary) > (SELECT avg(employee_salary) FROM employee)),
            employee_name ,null) employee_name 
    FROM employee
    group by employee_name,employee_salary