Sql query for many to one
2 answers
This is a database independent solution
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'
demo SQLFiddle
+3
source to share
May be:
SELECT DISTINCT sd.StaffId
FROM StaffDepartmentAssgnment sd
WHERE sd.DepartmentId = 'Dept2'
Update
S1 is not in Dept2 now, it was moved to Dept1 ... I need to pick up the top AssignedFromDate
Since you are using SQL-Server, you can use CTE
with the function 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'
+2
source to share