Click here to Skip to main content
15,921,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am trying to get the date difference between two rows in sql. I want to get number of days between EventTypeDec 'Match' and 'Accommodate' where EventType is in 11 and 15.


CSS
ID  EventTypeID EventType   ScheduledCompletion EventTypeDes
2   39           11         04/12/2012   18:58     Match
2   267          15         07/12/2012   21:00     Accommodate
2   383          11         10/12/2012   18:50     Match
2   3103         15         06/02/2013   16:30     Accommodate


Desired output
CSS
ID  EventTypeID EventType   ScheduledCompletion EventTypeDes    NumDays
2   39              11         04/12/2012 18:58    Match
2   267             15         07/12/2012 21:00    Accommodate       3
2   383             11         10/12/2012 18:50    Match
2   3103            15         06/02/2013 16:30    Accommodate      50(roughly)



I know how to use date difference function between two columns but no idea how to use it in two rows.
Would appreciate any help. Thanks in advance
Posted

Your core issue is that each pair does not have a unique id. If they did, this would be a lot easier. As it is, you need to just order by dates.

SQL
select id, eventtypeid, eventtype, ScheduledCompletion, EventTypeDes,
datediff(day,
lag(ScheduledCompletion, 1, getdate()) over (order by ScheduledCompletion), ScheduledCompletion) as Gap
from tblTest


will work in SS2012. You can add a case statement to not return a value for the 'match' rows. It would be much neater if you had a sane DB structure then it could easily be done with CTEs, and for SS2008 or 2005. It could still be done for 2005 or 2008 but I don't want to do any more until I know which one you're using, and why your DB structure is broken.

Here it is for SS 2008

SQL
with tbl as
(
 select row_number() over (order by scheduledcompletion) as r, id, eventtypeid, eventtype, scheduledcompletion, eventtypedes from tbltest
)

select r1.id, r1.eventtypeid, r1.eventtype, r1.scheduledcompletion, r1.eventtypedes,
case when r1.eventtype = 11 then '' else
convert(varchar(5),
datediff(day,
r2.ScheduledCompletion, r1.ScheduledCompletion)) end as Gap
from tbl r1 left join tbl r2 on r1.r = r2.r+1
 
Share this answer
 
v2
Comments
Jörgen Andersson 21-Jan-14 1:37am    
+5
Christian Graus 21-Jan-14 2:37am    
*grin* thanks. I threatened to not do a SS2008 solution, but then the afternoon dragged, so I thought 'why not' ?
Since you cannot use such function between different rows you have to make a inner join on the EventType field and then apply the function to the join result.
 
Share this answer
 
Comments
chan200uk 20-Jan-14 9:05am    
Thanks for the reply, any example please

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900