Search code examples
sqlsql-servert-sqlgaps-and-islands

Query SQL group by per next row if have same value?


How to do group by if the value of the next column is the same, later I will calculate how long the purchase will take, later added per group

enter image description here


Solution

  • This is a classic Gaps-and-Islands Problem.

    In the future, please provide sample data as TEXT not as an image.

    Example

    with cte as (
        Select *
              ,Grp = row_number() over (order by ID) 
                    -row_number() over (partition by BUAH order by ID)
        From  YourTable
    )
    Select BUAH
          ,Cnt = sum(1)
     From cte
     Group By BUAH,Grp
     Order By min(ID)   --<< Optional
    

    Results

    BUAH    Cnt
    APEL    2
    TOMAT   2
    APEL    3
    ...