需要从3个表中检索列

时间:2018-05-24 09:21:42

标签: sql sql-server tsql

有三个表:deptempsal。您可以在图像中找到它们的结构和数据。 我需要提取具有位置为pune并且在其部门中具有最高薪水的员工列表。由于有五个部门,最终输出将包含五行emp_iddeptdept_idsalary

Description of tables Expected output

我试过......

  select e.emp_id, dept,e.dept_id, max(sal) as 'highest salary'
    from sal s,emp e,dept d
   where e.emp_id = s.emp_id and d.dept_id = e.dept_id and loc ='Pune'
group by e.emp_id,e.dept_id,dept
order by e.dept_id 

2 个答案:

答案 0 :(得分:0)

除非您有窗口函数(取决于您使用的是MySQLOracleSQLite等),否则您需要执行此操作分两步。

找到每个部门的最高工资(对于'Pune'中的员工),然后找到另一组连接以找出这些人是谁。

SELECT
  dep.dept,
  dep.dept_id,
  emp.emp_id,
  sal.sal
FROM
  emp
INNER JOIN
  sal
    ON sal.emp_id = emp.emp_id
INNER JOIN
(
  SELECT
    emp.dept_id,
    MAX(sal.sal)  AS max_sal
  FROM
    emp
  INNER JOIN
    sal
      ON sal.emp_id = emp.emp_id
  WHERE
    emp.loc = 'Pune'
)
  dep_sal
    ON  dep_sal.dept_id = emp.dept_id
    AND dep_sal.max_sal = sal.sal
INNER JOIN
  dep
    ON dep.dept_id = emp.dept_id
WHERE
  emp.loc = 'Pune'
ORDER BY
  dep.dept,
  emp.emp_id

编辑: 随着SQL Server 2008的发展,它会更容易......

WITH
  emp_sal_ranked AS
(
  SELECT
    emp.dept_id,
    emp.emp_id,
    sal.sal,
    RANK(sal.sal) OVER (PARTITION BY emp.dept_id
                            ORDER BY sal.sal
                       )
                         AS rank_sal
  FROM
    emp
  INNER JOIN
    sal
      ON sal.emp_id = emp.emp_id
  WHERE
    emp.loc = 'Pune'
)
SELECT
  dep.dept,
  dep.dept_id,
  emp_sal_ranked.emp_id,
  emp_sal_ranked.sal
FROM
  emp_sal_ranked
INNER JOIN
  dept
    ON dept.dept_id = emp_sal_ranked.dept_id
WHERE
  emp_sal_ranked.rank_sal = 1
ORDER BY
  dep.dept,
  emp_sal_ranked.emp_id

答案 1 :(得分:0)

我会使用apply

select t.emp_id, d.dept, d.dept_id, t.sal
from dept d
cross apply ( select top 1 e.emp_id, s.sal as sal
              from emp e 
              inner join sal s on s.emp_id = e.emp_id
              where d.dept_id = e.dept_id and e.loc = 'Pune'
              order by s.sal desc
            ) t;