2016-07-28 2 views
1

ecto 쿼리를 수행하고 있으며 q.created_date으로 그룹화하려고합니다. 이 쿼리는 GROUP BY를 성공적으로 수행하지만 두 번째로 수행합니다. 나는 그 대신에 그룹화하려고 노력하고있다. 당신은 PostgreSQL을에 달 추출 date_part('month', field)fragment을 사용할 수 있습니다datetime 필드에 group_by MONTH를 수행하는 Ecto 쿼리를 작성하는 방법

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

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

같은 뭔가가 있나요? PostgreSQL? – Dogbert

+0

예, PostgreSQL. – gkkirsch

답변

4

: 사용중인 데이터베이스 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] 
+0

'date_part'와'date_trunc'의 차이점을 기억하십시오. 중복되지 않는 그룹화에는 trunc를 사용하십시오. – arvidkahl