I have a simple attribute table structured in this way:

Features Attribute1 Attribute2 Attribute3 Attribute4 Count
F1 5 0 1 3 3
F2 0 0 0 4 1
F3 1 2 0 0 2
F4 12 4 6 9 4

And I need to populate the 'Count' field depending on how many attributes have a value different from 0. In Excel I would use a simple Countif function such as Countif(Attribute1:Attribute4; "<>0"). In QGIS I tried to use this:

COUNT(CASE WHEN Attribute1 <> 0 THEN 1 END) +
COUNT(CASE WHEN Attribute2 <> 0 THEN 1 END) +
COUNT(CASE WHEN Attribute3 <> 0 THEN 1 END) +
COUNT(CASE WHEN Attribute4 <> 0 THEN 1 END) +

but I don't get the right result.

1 Answer 1


This expression gives you what you need:

  'ar', array(Attribute1, Attribute2, Attribute3, Attribute4),
  array_length(@ar) - array_count(@ar, 0)

with_variable assigns the second argument to the first argument to use it in the third argument that is an expression.

ar = array(Attribute1, Attribute2, Attribute3, Attribute4)

array_length(@ar) returns the length of the array. array_count(@ar, 0) counts the number of occurrences of a given value in the array. And array_length(@ar) - array_count(@ar, 0) gives you the number of fields that are different from 0.

enter image description here

  • Where will you save this information? We added the previous value as a new column to the records in the table. Mar 4 at 6:42
  • 1
    You can open a new thread for this question Mar 5 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.