• Hello Erlang,

    Many thanks for your reply. Couple of days ago, I found a solution, check the following please :

    with cte_test (DatetimeStamp,Packcount,WorkOrderID,RowID)

    AS

    (

    SELECT *,ROW_NUMBER() OVER (Order by X.Datetimestamp) RowID FROM

    (

    SELECT * FROM

    (

    select top(1) DateTimeSTamp,PackCount,WorkOrderID from Production

    where DateTimeStamp<@StartTime and WorkOrderID=@WorkOrderID

    order by DateTimeStamp DESC

    ) minusrow

    UNION

    select DateTimeSTamp,PackCount,WorkOrderID from Production

    where DateTimeStamp>@StartTime and WorkOrderID=@WorkOrderID AND DateTimeStamp<=@EndTime

    UNION

    select * from

    (

    select top(1) DateTimeSTamp,PackCount,WorkOrderID from Production

    where DateTimeStamp>@@EndTime and WorkOrderID=@WorkOrderID

    order by DateTimeStamp ASC

    ) plusrow

    ) X

    )

    INSERT INTO @teml

    select * from cte_test

    SELECT * FROM @temp A INNER JOIN @temp B ON a.RowID=b.RowID-1)

    Today, I visited the forum to check if there are any messages and I saw your solution and it seems we both thought exactly the same 🙂