使用inserted_at列按天/周/月分组行 示例:如果在1周之前创建第一行,则按天分组,如果在中间日期未创建任何数据,则将o添加为值。
[
{"21 Jul" => 12},{"22 Jul" => 0},{"23 Jul" => 3}, {"24 Jul" => 1}...
{"5 Aug" => 0}
]
提前致谢。
答案 0 :(得分:0)
It's not quite clear from the question exactly what is required, but hopefully the following query helps: It will give you the count of records grouped by the date part of inserted_at
.
defmodule CountByDateQuery do
import Ecto.Query
@doc "to_char function for formatting datetime as dd MON YYYY"
defmacro to_char(field, format) do
quote do
fragment("to_char(?, ?)", unquote(field), unquote(format))
end
end
@doc "Builds a query with row counts per inserted_at date"
def row_counts_by_date do
from record in SomeTable,
group_by: to_char(record.inserted_at, "dd Mon YYYY"),
select: {to_char(record.inserted_at, "dd Mon YYYY"), count(record.id)}
end
end
Usage:
row_counts_by_date() |> Repo.all() |> Map.new()
%{"05 Aug 2017" => 2}
答案 1 :(得分:0)
让我们假设您有名为starts_at
的带有DateTime字段的事件架构。
例如,要获取事件按日期计数的信息,可以使用以下功能:
def get_events_count_grouped_by_date(query) do
query
|> group_by([e], fragment("date(?)", e.starts_at))
|> select([e], %{date: fragment("date(?)", e.starts_at), count: count(e.id)})
|> order_by([e], asc: fragment("date(?)", e.starts_at))
end
然后像这样使用它:
Event |> get_events_count_grouped_by_date() |> Repo.all()