如何编写在日期时间字段上执行group_by MONTH的Ecto查询

时间:2016-07-28 23:37:10

标签: elixir phoenix-framework ecto

我正在进行ecto查询,并尝试按q.created_date进行分组。此查询成功执行GROUP BY,但它在第二次执行。我试图按月分组。

MYQUERY |> group_by([q], [q.created_date, q.id])

是否有类似的东西:

MYQUERY |> group_by([q], [month(q.created_date), q.id])

1 个答案:

答案 0 :(得分:5)

您可以fragment使用date_part('month', field)在PostgreSQL中提取月份:fragment("date_part('month', ?)", p.inserted_at))

iex(1)> from(Post) |> select([p], p.inserted_at) |> Repo.all
[debug] QUERY OK db=1.1ms queue=0.1ms
SELECT p0."inserted_at" FROM "posts" AS p0 []
[#Ecto.DateTime<2000-01-01 00:00:00>, #Ecto.DateTime<2000-02-02 00:00:00>,
 #Ecto.DateTime<2000-03-03 00:00:00>, #Ecto.DateTime<2000-04-04 00:00:00>,
 #Ecto.DateTime<2000-04-02 00:00:00>, #Ecto.DateTime<2000-03-02 00:00:00>,
 #Ecto.DateTime<2000-02-02 00:00:00>, #Ecto.DateTime<2000-01-02 00:00:00>]
iex(2)> from(Post) |> group_by([p], fragment("date_part('month', ?)", p.inserted_at)) |> select([p], count("*")) |> Repo.all
[debug] QUERY OK db=1.7ms
SELECT count('*') FROM "posts" AS p0 GROUP BY date_part('month', p0."inserted_at") []
[2, 2, 2, 2]