如何编写对日期时间字段执行group_by MONTH的Ecto查询 [英] How to write a Ecto query that does a group_by MONTH on a datetime field

查看:105
本文介绍了如何编写对日期时间字段执行group_by MONTH的Ecto查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行ecto查询,并尝试按q.created_date分组.该查询成功执行了GROUP BY,但第二次执行了GROUP BY.我正尝试按月分组.

I am doing a ecto query and am trying to group by q.created_date. This query successfully does the GROUP BY but it does it by the second. I am trying to group by month instead.

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

有没有类似的东西

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

推荐答案

您可以将fragment

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]

这篇关于如何编写对日期时间字段执行group_by MONTH的Ecto查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆