Select by column

I have a Postgres view with 4 columns, two of them contains numbers. I want to create a function to get the sum of the elements depending on the column name.

This query is working well:

def sum_by_colum(column) do
  Repo.aggregate(VwClientNodeBatteryStatus, :sum, column)

But I want to use something like:

from(vw in VwClientNodeBatteryStatus,
    select: sum(vw.^column))

Because I can use to get the popular {:ok, result} tuple. But I’m getting the following error:
`vw.^(column) is not a valid query expression. If you want to invoke vw.^/1 in a query, make sure that the module vw is required and that ^/1 is a macro

I guess Elixir/Ecto thinks that I have vw is a function. =S

1 Like

You’ll want to use field/2 ( to dynamically reference column names.

Untested code, but something like:
select sum(field(vw, ^column))


@gregvaughn You are the best! Thank you!