Skip to content
Advertisement

Sql assign unique key to groups having particular pattern

Hi I was trying to group data based on a particular pattern.

I have a table with two column as below,

I need to generate a key column that increment only after rollingsum equals 0 is encountered.As given below

I am using postgres, I tried to increment variable in case statement as below

But I am getting an error near :

Thanks in advance for all help

Advertisement

Answer

You need an ordering columns because the results depend on the ordering of the rows — and SQL tables represent unordered sets.

Then do a cumulative sum of the 0 counts from the end of the data. That is in reverse order, so subtract that from the total:

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