2016-06-08 70 views
0

我試圖獲得特定列的總和。 我有一個訂單模式,總場地,存儲總價格。 現在我試圖創建一個將總計所有訂單的總價值的查詢,但不知道我是否做得正確。 這裏是我到目前爲止有:Elixir/Phoenix列的總和

def create(conn, %{"statistic" => %{"date_from" => %{"day" => day_from, "month" => month_from, "year" => year_from}}}) do 

date_from = Ecto.DateTime.cast!({{year_from, month_from, day_from}, {0, 0, 0, 0}}) 
revenue = Repo.all(from p in Order, where: p.inserted_at >= ^date_from, select: sum(p.total)) 

render(conn, "result.html", revenue: revenue) 
end 

而只是調用它像html.eex <%= @revenue %>。 截至目前,它不會返回錯誤,只是在頁面上呈現隨機符號,而不是總收入。

我想我的查詢是錯誤的,但找不到有關如何使其正常工作的良好信息。任何幫助表示感謝,謝謝!

+0

是否使用的是外生的版本? – Gazler

+1

試試'Repo.one'而不是'Repo.all'。 – Dogbert

+0

@Dogbert該死的,不敢相信我犯了這個錯誤,謝謝! – Ilya

回答

4

您的查詢只返回1個值,並且Repo.all將其包裝在一個列表中。當您使用<%= ... %>打印列表時,它會將列表中的整數視爲Unicode代碼點,並將該代碼點作爲頁面上的輸出。修正是使用Repo.one來代替,它將直接返回值,在這種情況下是一個整數。

revenue = Repo.one(from p in Order, where: p.inserted_at >= ^date_from, select: sum(p.total)) 
+0

哦,這就是爲什麼我得到不同的符號,而不是價值。感謝精心製作! – Ilya

2

@ Dogbert的回答是正確的。值得注意的是,如果你使用的是外生2.0(目前處於發行候選版),那麼你可以使用Repo.aggregate/4

revenue = Repo.aggregate(from p in Order, where: p.inserted_at >= ^date_from, :sum, :total)