Rails按查询分组

时间:2015-03-02 17:18:41

标签: mysql ruby-on-rails ruby

我有这种方法来返回报告。这将返回如下内容:

+------------+----+---------+--------+----------+
|   dates    | id |  name   | amount | purchase |
+------------+----+---------+--------+----------+
| 2015-02-10 |  1 | Private |    100 |       30 |
| 2015-02-10 |  2 | Public  |    250 |       45 |
| 2015-02-20 |  1 | Private |    200 |       20 |
| 2015-02-20 |  2 | Public  |    150 |       25 |
+------------+----+---------+--------+----------+

获得此表后,我想在amount中应用加价百分比。日期之间的百分比不同。下面是标记后的表格。对于2015-02-10日期,2015-02-20的百分比为10%和20%。

+------------+----+---------+--------+----------+
|   dates    | id |  name   | amount | purchase |
+------------+----+---------+--------+----------+
| 2015-02-10 |  1 | Private |    110 |       30 |
| 2015-02-10 |  2 | Public  |    275 |       45 |
| 2015-02-20 |  1 | Private |    240 |       20 |
| 2015-02-20 |  2 | Public  |    180 |       25 |
+------------+----+---------+--------+----------+

到目前为止,这是我的代码。

def self.report(school_id)
  items = Transaction.joins("JOIN categories ON categories.id = transactions.category_id")

  items = items.select("date(from_unixtime(transactions.unix_timestamp)) as dates")
  items = items.select("categories.id")
  items = items.select("categories.name")
  items = items.select("sum(transactions.amount) as amount")
  items = items.select("avg(transactions.purchase) as purchase")

  items = items.where("categories.school_id = ?", school_id)

  items = items.group("categories.id")
  items = items.group("date(from_unixtime(transactions.unix_timestamp))")

  items.map do |x|
    p = Percentage.where(date: 'x[:dates]').limit(1).first.percentage
    x[:amount] = x[amount] * (100 + p) / 100
  end

  items
end

在标记过程之后,我想按id对它们进行分组,预期结果是这样的。金额将被汇总,购买将被平均。

+----+---------+--------+----------+
| id |  name   | amount | purchase |
+----+---------+--------+----------+
|  1 | Private |    350 |       25 |
|  2 | Public  |    455 |       35 |
+----+---------+--------+----------+

我对如何按id对其进行分组感到困惑,因为我尝试使用items.group(...)并且项目未分组。

1 个答案:

答案 0 :(得分:0)

尝试更改此行:

items = items.select("sum(transactions.amount) as amount")

items = items.select("sum(CASE WHEN DATE(dates)=DATE('2015-02-10') THEN transactions.amount*1.1 WHEN DATE(dates)=DATE('2015-02-20') THEN transactions.amount*1.2 ELSE transactions.amount END) as amount")