I have a query that sums up totals from within a date range using Postgres’ filter
(e.g. select sum(p.total) filter (where "date" >= first and "date" <= last)
), and I’d like to avoid some of the repetition if I can, I have to fetch a lot of columns so the code gets difficult to read fairly quick.
The best I have so far is
select: %{
total: sum(p.total) |> in_range(p.date, ^first, ^last),
other: sum(p.other) |> in_range(p.date, ^first, ^last),
}
And the in_range
macro looks like
defmacro in_range(sum_expression, date_col, start_date, end_date) do
quote do
unquote(sum_expression)
|> filter(
unquote(date_col) >= unquote(start_date) and unquote(date_col) <= unquote(end_date)
)
|> coalesce(0)
end
end
Is there some way I can restructure the code so that I can avoid the repetition? I was thinking something like the block below, but I know it is incorrect
sum_in_range = in_range(p.date, ^first, ^last)
select: %{
total: sum(p.total) |> sum_in_range,
other: sum(p.other) |> sum_in_range
}