SQL中的Sum运算

时间:2013-06-13 10:01:09

标签: sql

我创建了两个表,一个是“Employees”表和“Department”表。

部门表列名称为:

Dept_ID, Dept_Name 

我在这里为Dept_ID

指定了主键

员工表列名称为:

Emp_ID, FName, LName, City, Emp_Salary, Dept_ID

我在这里为Emp_ID&分配了主键。 Dept_ID引用的外键 Department(Dept_ID)

我想知道获得第二高薪的部门名称。我需要语法

请帮忙

2 个答案:

答案 0 :(得分:1)

对于Oracle,这将导致以下查询:

SELECT d.Dept_Name
FROM (
  SELECT rownum AS position, a.*
  FROM (
    SELECT Dept_ID, SUM(Emp_Salary) as Total_Salary
    FROM employees
    GROUP BY Dept_ID
    ORDER BY Total_Salary DESC
  ) a
) b
INNER JOIN department d ON d.Dept_ID = b.Dept_ID
WHERE b.position = 2

您可以在此处查看有效的Oracle SQLFiddle示例:http://sqlfiddle.com/#!4/f5602/17

为了完整起见,如果你的DBMS是MySQL,那么这个查询就可以解决问题:

SELECT d.Dept_Name
FROM (
  SELECT Dept_ID, SUM(Emp_Salary) as Total_Salary
  FROM employees
  GROUP BY Dept_ID
  ORDER BY Total_Salary DESC
  LIMIT 1,1
) a
INNER JOIN department d ON d.Dept_ID = a.Dept_ID

您可以在此处看到一个有效的MySQL SQLFiddle示例:http://sqlfiddle.com/#!2/738e0/15

答案 1 :(得分:0)

如果这是MSSQL,请尝试以下查询:

with salary as --sum all salaries for all departments
(
    select d.Dept_ID, SUM(e.Emp_Salary) as SalarySum
    from Department d
    inner join Employees e on e.Dept_ID = d.Dept_ID
    group by d.Dept_ID
),
max as --select maximum salary
(
    select  MAX(s.SalarySum) as Max
    from salary s
)

select top 1 * 
from salary s
where s.SalarySum < (select top 1 m.Max from max m) -- only select those that are lower than max
order by s.SalarySum desc