Search code examples
sql-servert-sqlwindow-functionsrow-number

How do I incrementally assign batch numbers to related rows in SQL Server?


How do I incrementally assign batch numbers in a time-ordered table if I want the batch numbers to increase if either of 2 fields changes? This is the original table:

Customer  Item     Time    
A         Apples   1:00 PM  
A         Apples   1:10 PM  
A         Oranges  1:20 PM  
A         Apples   1:30 PM  
B         Oranges  1:40 PM  
A         Apples   1:50 PM  
C         Apples   2:00 PM  

What I would like to do is to assign a Batch number. Note that the first 2 rows are assigned the same number because they are both Customer A and Apples. Note that in the 4th row, we return to Apples with Customer A, but it's assigned the next batch number, not back to Batch 1:

Customer  Item     Time     Batch
A         Apples   1:00 PM  1
A         Apples   1:10 PM  1
A         Oranges  1:20 PM  2
A         Apples   1:30 PM  3
B         Oranges  1:40 PM  4
A         Apples   1:50 PM  5
C         Apples   2:00 PM  6

Solution

  • You could use LAG function to determine if one of the fields change. Use a running sum to number the changes:

    WITH cte AS (
        SELECT *, CASE
            WHEN LAG(Customer) OVER (ORDER BY Time) = Customer AND LAG(Item) OVER (ORDER BY Time) = Item THEN 0
            ELSE 1
        END AS chg
        FROM t
    )
    SELECT *, SUM(chg) OVER (ORDER BY Time) AS batch
    FROM cte