Sql-server – SQL Server 2012 window function

sql serversql-server-2012t-sql

I've the following table which holds status of jobs in a history table.

JobHistory

jobOrderId | dateAdded               | Status
-----------|-------------------------|-------
4909       | 2015-08-26 18:15:07.527 | OPEN
4909       | 2015-08-28 13:35:38.997 | CLOSE
4909       | 2015-08-31 12:16:29.787 | OPEN
4910       | 2015-08-27 12:16:42.72  | OPEN
4910       | 2015-08-28 17:04:43.617 | CLOSE
4910       | 2015-08-31 17:01:27.337 | OPEN
4911       | 2015-08-27 16:08:39.467 | OPEN

I would like to get the following output

jobOrderId | opendate   | closedate
-----------|------------|-----------
4909       | 2015-08-26 | 2015-08-28
4909       | 2015-08-31 | NULL
4910       | 2015-08-27 | 2015-08-28
4910       | 2015-08-31 | NULL
4911       | 2015-08-27 | NULL

Can any one suggest me how to get this kind of output using SQL Server 2012 window functions?

Best Answer

create table #jobhistory (JobOrderID int, dateAdded datetime, Status varchar(10))
go
insert into #jobHistory (JobOrderID, dateAdded, Status)
select 4909, '2015-08-26 18:15:07.527', 'OPEN' union all
select 4909, '2015-08-28 13:35:38.997', 'CLOSE' union all
select 4909, '2015-08-31 12:16:29.787', 'OPEN' union all
select 4910, '2015-08-27 12:16:42.72 ', 'OPEN' union all
select 4910, '2015-08-28 17:04:43.617', 'CLOSE' union all
select 4910, '2015-08-31 17:01:27.337', 'OPEN' union all
select 4911, '2015-08-27 16:08:39.467', 'OPEN';
go
; with c as(
select jobOrderID, dateAdded, Status, rank() over (partition by jobOrderID order by dateAdded asc) as rnk 
from #jobHistory 
)
select c.jobOrderID, OpenDate=convert(char(10), c.dateAdded, 120), CloseDate=convert(char(10), c2.dateAdded, 120)
from c
left join c as c2
on c.jobOrderID = c2.jobOrderID
and c.Status='OPEN'
and c2.Status='Close'
and c2.rnk = c.rnk+1
where c.Status='Open';