azure-cosmosdbazure-cosmosdb-sqlapi

How to round the result of an AVG in cosmosDB?


How to round the result of an aggregate operation (SUM, AVG, MAX, MIN) in CosmosDB?

After many tries I'm afraid to believe CosmosDb SQL API doesn't allow such types of queries or equivalent

How can I round for instance an avg of a random attribute?

pseudo query (doesn't work in cosmosDB):

SELECT ROUND(AVG(c.weight)) 
FROM c

The error

Failed to query item for container ContainerName:
 {"code":"BadRequest","message":"One of the input values is invalid.\r\nActivityId: a672d255-02f3-4f6d-bb8a-943ea70b803f, Windows/10.0.20348 cosmos-netstandard-sdk/3.18.0"}

Solution

  • I'm assuming you're getting an error regarding compositions of aggregates (though you didn't provide the exact error):

    "Compositions of aggregates and other expressions are not allowed."

    You cannot perform something like ROUND() on an aggregate function - ROUND() is applicable directly to a property (such as ROUND(c.weight) in your case).

    You'll need to round the non-rounded result (AVG(c.weight)) from Cosmos DB, in your code, as you would round any other number, using the math library function in whatever language you're using.