3

I have a shapefile with a number of features, each with a field called "region". I want to count the number of features corresponding to each region. Outputting a shapefile with one feature per region, and new field called "count". E.G. Latin America : 13, Europe : 5, Asia : 14 etc. How can achieve this?

enter image description here

3 Answers 3

2
  1. Add a new field with the expression count($id,group_by:="continent")
  2. Dissolve the layer by "continent" field
  3. Optional: remove the fields which are no longer valid or you dont need
  4. Run Split Vector Layer and choose "continent" as your UID field and shp as file type
2

Use Menu Pocessing / Toolbox / Aggregate (see documentation). For group by expression use theregion field.

To get the necessary values in the attribute table, set the region field to first_value and create a new field (highlighted with red frame in the screenshot) with Source Expression corresponding to your region field and the Aggregate Function set to count. Be sure the field has a corresponding field type and length, see screenshot:

enter image description here

1

Another solution implies the usage of a "Virtual Layer" through Layer > Add Layer > Add/Edit Virtual Layer....

Let's assume there is a polygon layer called 'grid_test' with its attribute table, see image below.

input

With the following query, it is possible to count the number of features corresponding to each region.

SELECT
    geometry,
    COUNT() AS "count"
FROM
    "grid_test"
GROUP BY
    "region"

result1

P.S. On the last image original polygons with modified transparency were also visualized.

Application of the GROUP_CONCAT() is optional, but can be used to aggregate the features' ids.

A new query will look like

SELECT
    geometry,
    COUNT() AS "count",
    GROUP_CONCAT("id") AS "ids"
FROM
    "grid_test"
GROUP BY
    "region"

And the new output will be the following

result2

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.