Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi I've got what should be a simple query but I'm not sure how to write it.I have a table which holds employee assignments to positions, which holds historical data.Eg:
Now, what I'm after for each employee is their current position based on the highest "StartDate" for that employee.So from the above table I want the results:
3 7663 1/02/2008 9834 81212 2/03/2008 2888
Can anyone help? Do I need a Group By? That clause always confuses me!!!Thanks!!!!
PeterNeo
Constraint Violating Yak Guru
357 Posts
Posted - 2008-03-19 : 06:58:59
SELECT T1.*FROM tbl T1INNER JOIN ( SELECT EmployeeId, MAX(StartDate) AS StartDate FROM tbl GROUP BY EmployeeId) T2 ON T1.EmployeeId = T2.EmployeeId AND T1.StartDate = T2.StartDate
robinsonpr
Starting Member
4 Posts
Posted - 2008-03-19 : 07:00:54
Wow that was quick. I think I understand what it's doing too which is a bonus! Many thanks for the help!!!
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-03-19 : 07:12:20
Or do it using SQL 2005 function
SELECT t.ID,t.EmployeeID,t.StartDate,t.PositionIDFROM(SELECT ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY StartDate DESC) AS RowNo,ID,EmployeeID,StartDate,PositionIDFROM EmployeeAssignments)tWHERE t.RowNo=1
robinsonpr
Starting Member
4 Posts
Posted - 2008-03-19 : 07:42:32
I'm actually using SQL2000 at the moment, it's in the process of migrating to 2005.Thanks for the insight
sodeep
Master Smack Fu Yak Hacker
7174 Posts
Posted - 2008-03-19 : 07:54:14
And you are placing this question in Transact-SQL 2005 forum.
robinsonpr
Starting Member
4 Posts
Posted - 2008-03-19 : 08:03:58
I didn't get any replies in the SQL Server 2000 forum, posted a few days ago. I could find a "vanilla SQL" forum.