sql查询多对一关系

时间:2013-02-11 12:39:19

标签: sql sql-server

我有一个包含3列的表

表:StaffDepartmentAssgnment

StaffId         DepartmentId          AssignedFromDate

S1              Dept1                 2013-02-08
S2              Dept1                 2013-02-08
S3              Dept2                 2013-02-01 
S1              Dept2                 2013-02-01

我想找出目前在Dept2中的所有StaffIds。如何为它编写查询?

2 个答案:

答案 0 :(得分:3)

这是一个独立于数据库引擎的解决方案

select * from 
( 
   select StaffId, max(AssignedFromDate) as adate
   from StaffDepartmentAssgnment 
   group by staffid
) x
inner join StaffDepartmentAssgnment y
      on y.staffid = x.staffid and adate = y.AssignedFromDate
where DepartmentId = 'dept2'

SQLFiddle demo

答案 1 :(得分:2)

也许:

SELECT DISTINCT sd.StaffId         
FROM StaffDepartmentAssgnment sd
WHERE sd.DepartmentId = 'Dept2'

<强>更新

  S1现在不在Dept2,他已经转移到Dept1..i需要拿起   顶部的AssignedFromDate

由于您使用的是SQL-Server,因此可以使用CTE ROW_NUMBER函数:

WITH CTE AS (
    SELECT sd.staffid, sd.DepartmentId,
           rn = Row_number() OVER ( 
                    Partition BY sd.staffid 
                    ORDER BY assignedfromdate DESC) 
    FROM   staffdepartmentassgnment sd) 
SELECT staffid 
FROM   cte 
WHERE  rn = 1 
AND    DepartmentId = 'Dept2'

Demo