Basically I need know how to select, group and where by an undetermined number of fields, my problem is, if I select using an approach like this where I can select fields dynamically:
asset_fields = [:name, :nemo]
price_fields = [:value, :generated_price_date, :price_date]
bonus_fields = [:value, :factor_date]
unit_fields = [:name, :iso]
from [a, u, p, b] in query,
select: { struct(a, ^asset_fields),
struct(p, ^price_fields),
struc(b, ^bonus_fields),
struct(u, ^unit_fields) }
I got an error:
** (Ecto.QueryError) it is not possible to return a map/struct subset of a fragment, you must explicitly return the desired individual fields in query:
And yes one of my joins is a subquery, and I can not do something like this sum(b.value) and fragment(“sum(? * ?)”, b.value, p.price), wich I need to calculate.
If I go with an approach like this:
from [a, u, p, b] in query,
select: %{ asset_name: a.name, asset_nemo: a.nemo,
price_value: p.price, price_generated_price_date: p.generated_price_date,
bonus_value: b.value, bonus_date: b.factor_date,
sum_quantity: sum(b.value),
sum_total: fragment("sum(? * ?)", b.value, p.price),
unit_name: u.name }
I can select all the fields that I want from the subquery (and not all of them) and I can do sum(b.value) and fragment(“sum(? * ?)”, b.value, p.price), but the problem is that I can not select the fields dynamically.
On the where part of my querie I’m going to do something like this:
attributes = [attribute_one: [1, 2], attribute_two: [3, 4]]
filter_by_multiple_attributes(query, attributes) do
Enum.reduce attributes, query, fn {k, v}, query ->
from [a, u, p, b] in query, where; field(a, ^k) in ^v
end
end
The group by part I think that could be very similar to the where part.