【问题标题】:Perform calculation on Ecto result对 Ecto 结果进行计算
【发布时间】:2017-11-27 18:00:18
【问题描述】:

我想对 Ecto 结果进行计算。我有一个 Products 表,其中有 (color, rating, brand_id, price)。我想按range (0-1, 1-2, 2-3, 3-4, 4-5) 和每个范围内的产品数量对评级进行分组。我对长生不老药和 ecto 很陌生。感谢所有帮助。

【问题讨论】:

  • 请向我们展示您最初的努力。
  • 取决于数据库,我猜这在数据库方面可能比在 Elixir 方面更容易做到。如果我是你,我会寻找一个 SQL 查询来创建你想要的范围。
  • 因为我还想按brand_id分组,并获取每个brand_id中的产品数量,并按价格分组。我不确定是否有办法在 1 个查询中做到这一点。所以我认为最好查询所有产品并执行计算以获得每个组的结果

标签: elixir phoenix-framework ecto


【解决方案1】:

这是一个简单的方法,它只使用floor 来获得评分范围的下限:

defmodule QueryHelpers
  @doc "floor function for postgres"
  defmacro floor(x) do
    quote do 
      fragment("floor(?)", unquote(x))
    end
  end
end

defmodule A
  import QueryHelpers

  def product_rating_counts() do
    from product in Product, 
    group_by: floor(product.rating),
    select: %{rating: floor(product.rating), count: count(1)}),
    order_by: [asc: 1]
  end
end

iex> Repo.all(A.product_rating_counts())
[%{count: 2, rating: #Decimal<1>}, 
 %{count: 1, rating: #Decimal<2>},
 %{count: 1, rating: #Decimal<4>}]

【讨论】:

  • 有没有办法在单个查询中执行 group_by 并计算多个列?因为我还想根据品牌 ID、颜色和价格进行分组和产品计数
猜你喜欢
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多