我有一个包含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。如何为它编写查询?
答案 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'
答案 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'