So using ecto query I have written a query like this
from t in activity, where: t.id == ^id, group_by: [t.user_id, t.role_id], select: %{inserted_at: t.inserted_at}
Since I can not use select without using an aggregate function. So what I need is that I need to choose the last element which is inserted for the cost field and it’s not possible to use aggregate on this. What are my options?
how can I achieve this?
also is there any alternative for group_by and I can achieve the same thing as group_by
So I re-read your post and didn’t quite understands what you meant by last element which is inserted for cost field? Does it mean latest inserted_at value where cost is not null? In which case could you not just filter out the null-s?
But, I’m not quite sure what you want when you say:
In your example 800 is the maximum value, which you could get using
from t in activity, select: %{cost: max(t.cost)}
What I really think you are looking for is something like this, which gives you the cost for the activity with the greatest inserted_at value (a.k.a. most recent as long as you are not putting future dates in that field):
from t in activity,
order_by: [desc: t.inserted_at],
limit: 1,
select: %{cost: t.cost}
You can change the column used in the order by clause if you’re wanting something a little different, like “the cost for the activity with the greatest user_id value.”