Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql query for many to one relationship

Tags:

sql

sql-server

I have a table with 3 columns

table: StaffDepartmentAssgnment

StaffId         DepartmentId          AssignedFromDate

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

I want to find out all the StaffIds which are currently in Dept2.How do i write a query for it?

like image 342
Prachi Pant Avatar asked Jan 24 '26 14:01

Prachi Pant


1 Answers

This is a DB engine 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'

SQLFiddle demo

like image 100
juergen d Avatar answered Jan 26 '26 06:01

juergen d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!