Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

RE:calculation using first record and next record 1

Status
Not open for further replies.

allyne

MIS
Feb 9, 2001
410
US
Hi Everyone,

I have a table that looks like:
LOG Date Start Stop
522747 12/1/15 0:00 [highlight #A40000]12/1/15 7:40[/highlight] 12/1/15 8:40
509655 12/1/15 0:00 [highlight #4E9A06]12/1/15 8:05[highlight #4E9A06][/highlight][/highlight] [highlight #A40000]12/1/15 8:25[highlight #A40000][/highlight][/highlight]
482436 12/1/15 0:00 12/1/15 8:41 [highlight #4E9A06]12/1/15 9:11[highlight #4E9A06][/highlight]
[/highlight]

What I need to do is to create a calculated field that will calculate the difference between the first record in the start field and do a date diff using the 2nd record in the stop field and continue using the 2nd record in the start field and using a date diff using the 3rd row of the stop field and so on. I undertand using the date diff for the calculation but can't figure out how to do the calculation using the next row below.

Thanks for all your help!
 
Depends on your version of SQL Server, since 2008 there is LAG and LEAD.

As an example here's a gap finder of a numeric sequence:

Code:
declare @sequencewithanomalies as table (num int);
insert into @sequencewithanomalies values (1),(2),(4),(5),(6),(6),(9),(9),(9),(10);

--detecting anomalies
Select num, 
 LEAD(num) over (order by num)        as LeadNum, 
(LEAD(num) over (order by num) -num)  as diff
from @sequencewithanomalies

--extracting anomalies
Select * from
(
Select num, 
(LEAD(num) over (order by num) -num)  as diff
from @sequencewithanomalies
) tmp
Where diff<>1

A diff of 1 is normal increment, A diff of 0 means a double number, as is the case with 6 once and 9 twice. A diff>1 means a gap of size diff-1, obviously.
The nature of diff with datetimes is of course either a gap in time or an overlap in time. Does the start and stop time come from getDate(), from server time? Or does it come in from the client application as local system time? Then you can easily get such gaps or overlaps, just to give one reason for them.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top