Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a query by sum of two columns in Ecto?

Tags:

elixir

ecto

Trying to do something like this:

(from f in Foo,
 where: f.bar >= ^bar,
 order_by: f.cost1 + f.cost2,
 limit: 1) |> Repo.one

But it doesn't like the order by complaining about an invalid expression.

Also tried this:

(from f in Foo,
 select: %{id: id, total: fragment("cost1 + cost2 as total")},
 order_by: f.total,
 limit: 1) }> Repo.one

This one doesn't says column "f.total" does not exist.

Any ideas how to make this query work?

like image 428
DCameronMauch Avatar asked Aug 29 '16 19:08

DCameronMauch


People also ask

How do I write a query in Ecto?

The Ecto.Query module provides us with the Query DSL which we can use to write queries to retrieve data from the application’s repository. We can create a query with the Ecto.Query.from/2 macro. This function takes in two arguments: an expression and an optional keyword list.

How to order data by two columns in SQL?

How to Order By Two Columns in SQL? You need to display records from a given table sorted by two columns. Our database has a table named employee with the following columns: id, first_name, last_name, and salary.

How do you sum data in a query?

Sum data by using a Total row You can add a Total row to a query by opening your query in Datasheet view, adding the row, and then selecting the aggregate function that you want to use, such as Sum, Min, Max, or Avg. The steps in this section explain how to create a basic select query and add a Total row.

Can the select of each query be exactly the same?

The select of each query must be exactly the same, with the same types in the same order. Except expression returns only unique rows as if each query returned distinct results. This may cause a performance penalty.


1 Answers

I'm not sure why Ecto doesn't support order_by: f.cost1 + f.cost2, but your fragment syntax is incorrect. Here's the correct syntax:

(from f in Foo,
 where: f.bar >= ^bar,
 order_by: fragment("? + ?", f.cost1, f.cost2),
 limit: 1) |> Repo.one
like image 175
Dogbert Avatar answered Nov 01 '22 12:11

Dogbert