Hi, I've got a history of employment events theat looks something like this:create table #events(parentuid int,effdate datetime,shortdesc varchar(10))insert into #Events select 1743499,'Apr 22 2003 12:00AM', 'Employed'insert into #Events select 1743499,'Nov 13 2005 12:00AM', 'Maternity'insert into #Events select 1743499,'May 31 2006 12:00AM', 'Leaves'insert into #Events select 1743499,'Jun 1 2007 12:00AM', 'Transfer out event'
As part of a larger query I need to return this information so it looks something like this:Parentuid Event1 Effdate Event2 Effdate--------- ------- ------ -------- --------1743499 Employed 22/04/03 Maternity 13/11/051743499 Maternity 13/11/05 Leaves 31/05/061743499 Leaves 31/05/06 Transfer 01/06/071743499 Transfer 01/06/07 Now getdate()
I usually get this kind of info with 2 alias tables - one with the 'start' kind of events, and one with the 'end' type of events. I then join the 2 tables together where the 'start' dates are less than the 'end' dates. Like this:selectPS.parentuid,PS.effdate,PS.shortdesc,isnull(PE.Effdate, getdate()) effdate,isnull(PE.shortdesc, 'Right Now') shortdescfrom (select e.parentuid, e.effdate, e.shortdesc from #events e ) PSleft join (select e.parentuid, e.effdate, e.shortdesc from #events e ) PEon pe.parentuid = ps.parentuid and ps.effdate < pe.effdategroup by ps.parentuid, ps.effdate, ps.shortdesc, pe.effdate, pe.shortdescorder by ps.parentuiddrop table #events
Unfortunately I can't use this because there are no real 'start' or 'end' events - a person could be employed, then leave, then be re-employed, then go on maternity or part time, or they could start off on part time and move to employed etc. etc.So the only solution I've been able to come up with is to ID a temporary table, then join my 2 alias tables to each other on the 'start'.id = 'end'.id - 1. Like this:create table #events(ID int identity(1,1),parentuid int,effdate datetime,shortdesc varchar(20))insert into #Events select 1743499,'Apr 22 2003 12:00AM', 'Employed'insert into #Events select 1743499,'Nov 13 2005 12:00AM', 'Maternity'insert into #Events select 1743499,'May 31 2006 12:00AM', 'Leaves'insert into #Events select 1743499,'Jun 1 2007 12:00AM', 'Transfer out event'selectPS.parentuid,PS.effdate,PS.shortdesc,isnull(PE.Effdate, getdate()) effdate,isnull(PE.shortdesc, 'Right Now') shortdescfrom (select e.id, e.parentuid, e.effdate, e.shortdesc from #events e ) PSleft join (select e.id, e.parentuid, e.effdate, e.shortdesc from #events e ) PEon pe.parentuid = ps.parentuid and ps.id = pe.id -1group by ps.parentuid, ps.effdate, ps.shortdesc, pe.effdate, pe.shortdescorder by ps.parentuid
This seems to work fine but I was wondering if there was a more elegant way of getting what I needed?Cheers,Yonabout