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.
Author |
Topic |
wldodds
Starting Member
20 Posts |
Posted - 2012-09-09 : 10:34:48
|
I have a table which has multiple columns within it. Every time an event occurs for an employee a record is inserted into the table with an effective date.I'm trying to retrieve the record for employee's where I specify a date. For example, the table is called HR2EMP02 and it has columns employeeid and effectivedate.When the employee is created an initial record is created and then if a change is made to the employee a record is then inserted with an effectivedate.sample data:EmployeeId, EffectiveDate1234, 6/1/20121234, 7/28/20121234, 8/19/20124567, 7/3/20124567, 8/11/20124567, 9/8/2012When I run the query for as of 7/5/2012 I would like to return the following records:1234, 6/1/20124567, 7/3/2012I tried this but obviously only the top portion of this query works the exists part doesn't and I'm stumped:select * from HR2EMP02 T1where T1.EFFECTIVEDATE_I <= '6/20/2012' and T1.EFFECTIVEDATE_I exists (select * from HR2EMP02 T2 where T2.EFFECTIVEDATE_I <= '6/20/2012')Any help is greatly appreciated!Thanks, |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-09-09 : 12:00:42
|
[code]DECLARE @Date datetimeSET @Date = '2012-06-20'SELECT t.*FROM table tINNER JOIN (SELECT EmployeeId,MAX(EffectiveDate) AS MaxDate FROM table WHERE EffectiveDate < =@Date GROUP BY EmployeeId)t1ON t1.EmployeeId = t.EmployeeIdAND t1.MaxDate = t.EffectiveDate[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
wldodds
Starting Member
20 Posts |
Posted - 2012-09-09 : 20:17:16
|
Thank you that worked perfectly. I didn't think of an Inner Join I'm so used to always going with a left outer to pull all records. Greatly appreciated! |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-09-09 : 22:43:07
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|