catra

catra

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)
end

But I want to use something like:

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

Because I can use Repo.one 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

Most Liked

gregvaughn

gregvaughn

You’ll want to use field/2 (Ecto.Query.API — Ecto v3.14.0) to dynamically reference column names.

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

Last Post!

catra

catra

@gregvaughn You are the best! Thank you!

Where Next?

Popular in Chat/Questions Top

Fl4m3Ph03n1x
Background I am trying to do the typical Ceaser cypher exercise in Elixir. The description of the exercise is as follows: Create an impl...
New
Iex.new
Hello!, I just started this week to discover Elixir. I’m a PHP-Programmer and did some sutff in Go too. The more I read about Elixir t...
New
miguelsrrobo
hi i was wondering if it is necessary to learn erlang to learn elixir
New
loganhelms
A while back, I read a great book by Luis Atencio titled, Functional Programming in JavaScript. In section 7.3, he discusses memoization ...
New
stevensonmt
I’d like to provide my review of the Elixir Course module from Groxio. I have some criticisms but I’d like to start with the positives. ...
New
lgmfred
Hello, I want to get started with elixir today. Having learnt the basics of Erlang (my first ever language) and seen what it’s can do, I’...
New
marciol
Hey, I have very restricted resources and time so I’m trying to understand the best way to learn Liveview in terms of cost/time. The Pra...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54996 245
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

We're in Beta

About us Mission Statement