Use alias field in select ecto

Hi. I have a query that looks like this:

from p in Payment, group_by: fragment("extract(hour from ?) as hour", p.inserted_at),
select: {fragment("max(?)", p.amount)}
How can I get my group_by field (hour) in the select using this query?

Don’t quote me on this, but I don’t think it is possible.

I have a vague recollection of trying to order some results depending on the result of an expression in the select, and the only way to make it work was to repeat the expression verbatim in the order_by clause.

Unless I’m wrong, you’ll have to do

from p in Payment, group_by: fragment("extract(hour from ?) as hour", p.inserted_at),
  select: {
    fragment(max("?", p.amount)), 
    fragment("extract(hour from ?) as hour", p.inserted_at)
  }

and hope PostgreSQL is smart enough to compute that expression only once. Alternatively you can write a raw query.

Also be aware of this: https://github.com/elixir-ecto/ecto/issues/3159

I haven’t read the issue in detail, but looks suspiciously similar to the query I’ve suggested you to run, so worth keeping that in mind.

Definitely. that was the only way around I could find! Thanks for your detailed feedback.