Click here to Skip to main content
15,881,803 members
Articles / Database Development / SQL Server / SQL Server 2012
Tip/Trick

Read Data from the Next Row

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
21 Jun 2014CPOL 7.8K   3  
Read data from the next row

Introduction

In this article, I will show how to read data from the next row in one SELECT on the MSSQL 2008 and how it is easy to do that on MSSQL 2012 using one of the new 2012 functions.

Problem

Let's have the following TrainHistory table:

Image 1

We want to calculate the number of days between the current row and the next row in one SELECT.

Generally a cursor is used to achieve this work, but it is time consuming for huge data. I show here how to resolve the problem in one select statement on MSSQL-2008 and MSSQL-2012.

On MSSQL-2008 using CTE

SQL
WITH    CTE_TH 
          AS ( SELECT ROW_NUMBER() OVER ( PARTITION BY TrainID ORDER BY EventDate ) AS row_num 
                ,   TrainID
                ,   EventDate
                ,   Delay
                FROM TrainHistory 
             ) 
    SELECT T_CURRENT_ROW.* 
     ,   DATEDIFF(DAY, T_CURRENT_ROW.EventDate, T_NEXT_ROW.EventDate) AS days_without_delay 

 FROM CTE_TH T_CURRENT_ROW 
  LEFT JOIN CTE_TH T_NEXT_ROW 
            ON T_CURRENT_ROW.row_num + 1 = T_NEXT_ROW.row_num  
               AND T_CURRENT_ROW.TrainID = T_NEXT_ROW.TrainID

Results:

Image 2

On MSSQL 2012 Using the New LEAD Function

The LEAD function gives access to retrieve column from previous row or the next row.

We obtain the same results without any join:

SQL
SELECT
       TrainID,
       EventDate,
       Delay,
       DATEDIFF(DAY, EventDate, LEAD(EventDate) OVER (PARTITION BY TraindID ORDER BY EventDate)) AS days_without_delay
FROM TrainHistory

Image 3

History

  • 2014-06-21 First release

License

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


Written By
Software Developer
Canada Canada
C,C++,C#,X++,.NET,JavaScript,ASP.NET,MVC,jQuery,Ajax,HTML5,WCF,JAVA,PHP,PowerShell,SharePoint 2010/2013,Dynamics AX,MSSQL,SQLCLR,MySQL,Oracle,Sybase, SSIS,SSRS,Infragistics,BI,CrystalReports,ADO.NET,EntityFramework,Unix,C Shell,PERL,COBOL,Z/OS.

Comments and Discussions

 
-- There are no messages in this forum --