Skip to content
Advertisement

SQL Server – restart running count on change

The schema

Simplified, a sales table with non-unique sales IDs. Within each ID there will be a sale of an element S, which can be followed by a sale of up to two elements L linked to the element S. For example:

The expected outcome

Pivot the sales data with the expected outcome being:

My attempt

I’ve attempted to use ROW_NUMBER() OVER to count instances of L-elements assigned to each S-element but I don’t know how to reset the count after each new S-element. My query

Returns

Where I would like to see instead something like:

Which could be pivoted using the value in the cnt column.

Any help with the problem, or alternative approaches!, would be appreciated.

Advertisement

Answer

You really need something else than just non-unique ID to order by. Having just these two columns id and element is not enough. Tables in SQL don’t have any intrinsic order that you could rely on.

The code below that populates a temp table generates IDENTITY values in arbitrary order. In this specific example IDENTITY values happen to be generated in the same order as rows are written in the VALUES clause, but it is not guaranteed at all. This behaviour is undefined. You should never rely on this. Your data must have some sort of RowID.

Sample data

Query

Once you do have some unique RowID to order by, the query becomes a variation of gaps-and-islands. Your code was very close. You just need to subtract two sets of row-numbers.

Result

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement