Creating query function, where it sums all database values

I needed some help.

I’m trying to create a function, where I make a sum of all the values that are present in the Example column

Database there are the following columns

name | value

product 1 | 20
product 2 | 50
product 3 | 15.5

I need my form to query the products selected via multiple_select

If I select product 1 and product 3
The value should be 35.5

value = ["1", "3"]

The idea would be to use a
Repo.get(Example, rows)

would have an example?

A very dirty and very quick solution (if I understood you correctly):

iex::1> alias Ecto.Adapters.SQL
iex::2> %{rows: [[product_1_value], [product_3_value]]} = 
   SQL.query!(Your.Repo, "SELECT value FROM your_table WHERE name IN (product 1, product 3)")
iex::3> product_1_value + product_3_value
iex::4> 35.5

Try something like this:

values = ["1", "3"]
total = Repo.aggregate(from e in Example, where: e.name in ^values, :sum, :value)
2 Likes

or this:

values = [1, 3]
q = from x in your_table, where: x.name in ^values, select: x.value

q
|> Repo.all() 
|> Enum.sum()