内部联接与另一个表

时间:2015-06-02 09:43:03

标签: sql sql-server sql-server-2012 inner-join

**Table Employee** 

Id    Name
1     EmpName1
2     EmpName2
3     EmpName3

**Table EmpDeptHistory**

Id    EmpId    Dept        Date
1     1        Housing     2015-03-02
2     2        Finance     2015-01-03
3     1        WareHouse   2015-05-02
4     2        Housing     2015-02-06
5     3        WareHouse   2015-02-02
6     1        Housing     2015-05-01
7     2        Finance     2015-01-02
8     2        Housing     2015-05-04
9     2        Finance     2015-05-02
10    1        WareHouse   2015-03-08
11    1        Housing     2015-02-20

我需要找到每个员工最近工作的部门。此外,我需要通过EmpId

找到个别员工

以下查询仅返回一名员工,而不是全部:(

SELECT e.id, edh.dept,edh.date
FROM Employee e
  inner join (select top 1 eh.empid, eh.dept, eh.date
              from EmpDeptHistory eh
              order by eh.date desc) as edh
    on e.id=edh.empid

是的,我知道前1名将根据日期给出emp id,因此只显示一个员工详细信息。我不知道如何让所有员工最近获得部门。

select e.id,edh.dept,edh.date
from employee e
  inner join EmpDeptHistory edh
    on e.id = (Select eh.empid, eh.dept, eh.date   
               from EmpDeptHistory eh
               where e.id=eh.empid
               order by eh.date desc)

以上投掷

  

ORDER BY子句在视图,内联函数中派生无效   表,子查询和公用表表达式,除非TOP,   还指定了OFFSET或FOR XML。

3 个答案:

答案 0 :(得分:4)

您可以使用CROSS APPLY为每个左侧行运行右侧子查询一次:

SELECT e.id, edh.dept,edh.date
FROM Employee e cross apply ( select top 1 eh.empid, eh.dept, eh.date from  
EmpDeptHistory eh where eh.empid = e.id order by eh.date desc) as edh

答案 1 :(得分:3)

您可以使用CTE和排名函数,例如ROW_NUMBER

WITH CTE AS
(
    SELECT e.id, edh.dept, edh.date,
           rn = ROW_NUMBER() OVER (PARTITION BY edh.EmpId ORDER BY edh.date DESC)
    FROM Employee e inner join EmpDeptHistory edh  
       on e.id = edh.empid
)
SELECT id, dept, date
FROM CTE
WHERE rn = 1

DEMO

答案 2 :(得分:1)

对于每位员工的最新部门,您可以这样做:

SELECT t1.*
FROM EmpDeptHistory t1 INNER JOIN 
(
   SELECT EmpId, MAX(Date) [Date] 
   FROM EmpDeptHistory 
   GROUP BY EmpId
) AS t2 
    ON t1.EmpId = t2.EmpId AND t1.Date = t2.Date

如果需要,可以将EmpId放入where子句中。