我有这个方法来返返回告。这将返回如下内容:
+------------+----+---------+--------+----------+
| 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 |
+------------+----+---------+--------+----------+
获得此表后,我想在金额
中应用加价百分比。日期之间的百分比有所不同。下面是标记后的表格。对于 2015 年 2 月 10 日,该百分比为 10%;对于 2015 年 2 月 20 日,该百分比为 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(...)
但项目未分组。
最佳答案
尝试更改此行:
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")
关于mysql - Rails 按查询分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815725/