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?
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 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With