QGIS 3.22 Aggregate elements from the same layer

Viewed 439

I have one layer that represents several land cover categories each identified thanks to a code. I want to aggregate the number of objects each category has for a subset of code (i.e. from 111:113 how many objects do I have, from 114:222 how many objects do I have? etc.) How can I do it from the attribute table? I thought about the field calculator, and added the following function:

aggregate

Can someone help?

1 Answers

The expression to use is:

count ("code_90", group_by:= "code_90" in (111,112,113))

This counts the features that contain a value of 111, 112 or 113 in the field code_90.


To automatically create a range of values (like from 114 to 222), use this expression:

count ("code_90", group_by:= array_contains (generate_series (114,222), "code_90" ))

This counts the features that contain a value from 114 to 222.


To count the number of several ranges at once, use a CASE condition:

case 
when array_contains (generate_series (111,113), "code_90" ) then count ("code_90", group_by:= array_contains (generate_series (111,113), "code_90" ))
when array_contains (generate_series (114,122), "code_90" ) then count ("code_90", group_by:= array_contains (generate_series (114,122), "code_90" ))
when array_contains (generate_series (123,133), "code_90" ) then count ("code_90", group_by:= array_contains (generate_series (123,133), "code_90" ))
when array_contains (generate_series (134,144), "code_90" ) then count ("code_90", group_by:= array_contains (generate_series (134,144), "code_90" ))
end

This counts the features for the following 4 ranges: 111 to 113, 114 to 122, 123 to 133 and 134 to 144.


The same, but without manually define a line for each range. Define the ranges once in line 4 inside the brackets (here 4 ranges: 111 to 113 / 114 to 122 / 123 to 133 / 134 to 144) to then get the correct count for all ranges:

array_max(
    with_variable (
        'list',
        'map(111,113,114,122,123,133,134,144)',
        array_foreach(
            map_akeys( eval(@list)),
            case
                when array_contains (generate_series (@element,map_get( eval(@list),@element)), "code_90" ) 
                then count ("code_90", group_by:= array_contains (generate_series (@element,map_get( eval(@list),@element)), "code_90" ))
            end
        )
    )
)
Related