I have a polygon layer of ski resorts call skiResorts
. I have a liner layer of pistes called pistes
. The pistes layer has 2 several attributes and include aa_piste_length
and aa_piste_difficulty
. aa_piste_difficulty
includes 3 categories, namely, beginner
, intermediate
and advanced
.
In the skiResorts
layer, I would like to make 3 new calculated fields, namely, beginner_length
, intermediate_length
and advanced_length
which sums the value of aa_piste_length
. For example, beginner_length
in the skiResorts
layer would be the sum of all aa_piste_difficulty
that equals beginner
and is within that particular skiReport
polygon.
I am very confused as to how to do this. Do I need to make a one to many relationship between skiResorts and pistes? Can I just use aggregate in the Field Calculator to do this?
I have tried below but still have questions how to complete it.
aggregate(layer:= 'pistes',
aggregate:= 'sum',
expression:= ?? what does here?? ,
filter:= ?? how to say where piste_difficulty = beginner ??
)
Best Answer
First solution: use
overlay_intersects()
I recommend using
overlay_intersects()
function (available since QGIS 3.16). It is easier to handle when it involves (as here) spatial relationship (take into consideration only overlapping pistes).Use the follwong expression. You get an array of all
aa_piste_length
values from layerpistes
, filtered by the value defined at the end of line 5. Usearray_sum()
to get the sum:Second solution: use
aggregate()
Just for curiosity since you asked how to use
aggregate()
function. The expression argument is simply the field name whose values you want to sum. The filter, howver, has to take into consideration intersection features only as well as category values. The expression looks like this:Edit
See help of the
aggregate()
function how the optional filter expression to limit the features used for calculating the aggregate works:So here, we calculate the intersection of the geometry of the current (=joined) layer -
$geometry
- with the geometry of the source feature -geometry (@parent)
Remark: in QGIS versions 3.28 and later,
$geometry
is replaced by@geometry
.