Sorry for the confusion. I have below attached table sql server database table holding continuous and non continuous records. When i say continuous that means EP of first record if Beginning Point(BP). I need to write a query to transform such records into one record like shown in the target. Please help me build a query that can help me solve the purpose. (SQL Server 2014)

flatten records for continuous data

  • Order by BP,EP asc – Roxy Feb 23 '19 at 13:28
  • If i just group by order to get min(bp), max(ep), max(date) then there will be other records which are not continuous in the same order will be impacted. I need to flatten only continuous records. – Roxy Feb 23 '19 at 13:38
  • Query has to scan through each and every row to validate if the records are continuous or not continuous based on current record(EP)=LEAD(BP) to flatten and rest of the records that doesnt fit into this condition have to be selected as is. – Roxy Feb 23 '19 at 13:41

This appears to be a 'GAPS' and 'ISLAND' problem. The following example works against your test data.

--demo setup
Declare @Table1 table (BP decimal(5,1), EP decimal (5,1), Latest_Date date, [Order] varchar(10))
insert into @table1(BP,EP,Latest_Date,[Order]) values

--the solution
;WITH CTE_DataIslands -- First CTE determine the start of each new data island
AS (
    SELECT *
                WHEN (
                        LAG(EP, 1, - 1) OVER (
                            PARTITION BY [Order] ORDER BY BP
                                ,EP ASC
                        ) <> (BP)
                    THEN 1
                ELSE 0
            ) AS [IsNewDataIsland]
    FROM @Table1
AS (
        ,SUM([IsNewDataIsland]) OVER (
                ,ep ROWS UNBOUNDED PRECEDING
            ) AS GroupingID -- Create a running total of the IsNewDataIsland column this will create a grouping id we can now group on
    FROM CTE_DataIslands
    ,MAX([EP]) AS [BP]
    ,MAX(Latest_Date) AS Latest_Date
    ,MIN([order]) AS [Order]
FROM CTE_GenerateGroupingID

| BP    | BP    | Latest_Date | Order  |
| 136.0 | 144.8 | 2019-02-21  | UMT004 |
| 150.0 | 160.5 | 2019-02-17  | UMT004 |
| 170.0 | 190.3 | 2019-02-18  | UMT004 |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.