3

我有一个有 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 中的所有 StaffId。我如何为它编写查询?

4

2 回答 2

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 演示

于 2013-02-11T12:40:38.047 回答
2

也许:

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

更新

S1 现在不在 Dept2,他已经转移到 Dept1..我需要拿起最上面的 AssignedFromDate

由于您使用的是 SQL-Server,因此您可以将 aCTEROW_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'

演示

于 2013-02-11T12:41:32.837 回答