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.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Date comparisons

Author  Topic 

jnbreese
Starting Member

2 Posts

Posted - 2006-07-10 : 14:43:52
Okay, I'm stuck. I'm not sure if I'm posting this to the correct forum, so I appologize if this is off-topic...


I have table of payroll data (~2MM records), and I'm trying to figure out how long a given employee has held a particular job title (see sample data below).

Employee_ID Transaction_Date Job_Code Job_Title
10070 11/5/2004 104 Staff
10070 5/6/2005 104 Staff
10070 5/20/2005 108 Manager
10070 7/29/2005 108 Manager
10070 9/9/2005 108 Manager
10070 1/1/2006 121 Director
10070 3/1/2006 121 Director


So the results for this employee should be:

Staff 11/5/2004 - 5/19/2005
Manager 5/20/2005 - 12/31/2005
Director 1/1/2006 - 3/1/2006.

If I try to take the min(Transaction date) and max(transaction date) by employee id and job title, I'm left with gaps in job title history.

Any ideas?

Thanks in advance


SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-07-10 : 15:11:06
You need to normalize your tables.
-- prepare test data
declare @test table (Employee_ID int, Transaction_Date datetime, Job_Code tinyint, Job_Title varchar(8))

insert @test
select 10070, '11/5/2004', 104, 'Staff' union all
select 10070, '5/6/2005', 104, 'Staff' union all
select 10070, '5/20/2005', 108, 'Manager' union all
select 10070, '7/29/2005', 108, 'Manager' union all
select 10070, '9/9/2005', 108, 'Manager' union all
select 10070, '1/1/2006', 121, 'Director' union all
select 10070, '3/1/2006', 121, 'Director'

-- show test data
select * from @test

-- Do the work!
select t0.*,
(
select case
when min(transaction_date) is null then dateadd(day, datediff(day, 0, getdate()), 0)
else min(transaction_date) - 1
end
from @test t1
where t1.employee_id = t0.employee_id
and t1.transaction_date > t0.begindate
and t1.job_code <> t0.job_code
and t1.job_title <> t0.job_title
) enddate
from (
select employee_id,
min(transaction_date) begindate,
job_code,
job_title
from @test
group by employee_id,
job_code,
job_title
) t0
order by t0.employee_id,
t0.begindate

Peter Larsson
Helsingborg, Sweden
Go to Top of Page

jnbreese
Starting Member

2 Posts

Posted - 2006-07-10 : 15:29:54
Awesome! Thanks Peter
Go to Top of Page

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2006-07-11 : 07:30:24
Hi all,

Just a thought:

The code won't cope with people getting 'demoted' (e.g. going from Staff->Manager->Staff). I'm not surprised, because that makes it quite a bit trickier, but should that be a requirement?


Ryan Randall
www.monsoonmalabar.com London-based IT consultancy

Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page
   

- Advertisement -