QGIS Attribute Form – Creating Auto Incremental Field Filtered by Other Field Value

attribute-formfields-attributesqgisqgis-expressionunique value

From a point geometry layer with two categories "A" and "B", when I enter new points, I first choose the category of the "CATEG" field with a listbox, and then I use the following expression in the form properties to add a value in "ORDER" field for introducing an autoincremental value depending on the value of "CATEG" field:

if(maximum("ORDER") is NULL, 1, maximum("ORDER") + 1)

Screenshot of the form:

enter image description here

Screenshots of the form properties:

enter image description here

enter image description here

At the moment this workflow is not what my project needs because I can't get the autoincremental value to take into account the value of the "CATEG" field.

My goal is:

  • Enter a value and choose "A" or "B" in the "CATEG" field
  • If it is the first point for "A" or "B", then the "ORDER" field should be filled with the value 1
  • If it is the second point or later, then the "ORDER" field should be filled with the previous value +1

For example: if I enter a point with "CATEG"=A and the last value is 4, the "ORDER" field should be filled with the value 5. But if I choose "CATEG"=B and the last value is 2, the "ORDER" field should be filled with the value 3.

What expression could I use in the "ORDER" field form to make it work with this logic?

Best Answer

You need to specify the second parameter group_by as "CATEG" for the maximum() function.

if(maximum("ORDER", "CATEG") is NULL, 1, maximum("ORDER", "CATEG") + 1)

enter image description here