Create function to sum all values

Guys, I currently have a table called products in my database, and inside the products there is a column called “value”.

How do I create a function where I can sum all the values at once?
Note: All values are transformed to Float.

I want to call my template like this:
<%= ProjectWeb.Structure.Product.sum_value =>

Is it possible to do that?

Actually that is a built in function in SQL databases.

https://hexdocs.pm/ecto/Ecto.Query.API.html#sum/1

If however the data is already in memory as a list, just call.
Enum.sum/1.

4 Likes

In your example it would be something like this:

Repo.aggregate(ProjectWeb.Structure.Product, :sum, :sum_value)