3

I several times had the same problem using the QGIS expression aggregate: I got the impression that it behaves somehow buggy - or I make a mistake. See this expression I use on a point layer:

aggregate ( 
    layer:='points', 
    aggregate:='concatenate_unique',  
    expression:=x($geometry),
    concatenator:=','
)

The preview shows an error: Could not calculate aggregate for: x($geometry). If I click the arrow to the right of the preview to change to the preview for the next feature, the preview changes from error to NULL. As far as I can see, comparing with the help on the right side, the syntax is correct. Simplifying the expression to aggregate ('points','concatenate_unique', x($geometry)) results in exactely the same problem. I also changed the layer name to the @layer variable and used an existing field id to aggregate: aggregate (@layer,'concatenate_unique', "id" ). However, the very same problem persists.

Is this a bug or do I make a mistake?

QGIS expression aggregate

2
  • 1
    Maybe debug in your attribute table with a virtual field showing the content of x($geometry) ? Maybe one geometry is not correct ?
    – etrimaille
    Commented Dec 26, 2020 at 14:56
  • Geometry is correct. As mentioned, I also tried to use an existing attribute value instead of x($geometry), with the same error. I had this same problem for several times in different projects with different geometries and layers. So now I'm curious enough to find out if someone else can reproduce the error?
    – Babel
    Commented Dec 26, 2020 at 15:02

1 Answer 1

6

You need to convert your coordinates to a string first:

aggregate ( 
    layer:='points', 
    aggregate:='concatenate_unique',  
    expression:=to_string(x($geometry)),
    concatenator:=','
)

This is because double values cannot be concatenated as a string and therefore returning NULL or Could not calculate aggregate for: $geometry. So it is related to 'concatenate' as well as 'concatenate_unique'. Therefore an alternative would be to use 'array_agg' instead:

array_to_string( -- concatenate the array to a comma separated string, as specified in the last line of this expression
    array_distinct( -- keep only unique values in this array
        aggregate(
            layer:='points',
            aggregate:='array_agg', -- create the array
            expression:=x($geometry)
        )
    )
,',') -- use comma as separator for concatenation
0

Your Answer

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

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