Adding unique ID for consecutive groups using Field calculator in QGIS

expressionfield-calculatorgroupingqgisunique id

I found a similar question on this site and the answer suggested:

array_find(
    array_distinct(
        array_agg("PortCluster_ID")
        ),
        "PortCluster_ID"
    ) + 1

but using this expression gives me the following result (group1)

enter image description here

What I want to do is have what I wrote in white color on the attached image. As you can see I have consecutive "PortCluster_ID"s ordered in time, and i have a group of 119, then a group of 111 and then a group of 119 again, for this second group of 119 I want to have a new "ID".

What this data represents is fishing trips in and out of ports, some trips end in the same port (same "PortCluster_ID") but are obviously a different trip (ordered in ascending time).

Best Answer

create an ID field following the GpsTime field, then create the group1 field and populate it with the following expression (can be improved):

with_variable('cucu',
   aggregate( 
   layer:=@layer_name,
   aggregate:='array_agg',
   expression:=
   (array_find(array_agg("ID", "PortCluster_ID"),"ID"))-"ID"),
with_variable('cucu2',
   (array_find(array_agg("ID", "PortCluster_ID"),"ID"))-"ID",
   array_find(array_distinct(@cucu),@cucu2)+1))

enter image description here

the scheme used:

enter image description here

sample data: https://gist.github.com/pigreco/48cf061c183809b0e69628a13493f771