0
我有这种方法来返回报告。这将返回是这样的:我得到这个表Rails Group By Query
+------------+----+---------+--------+----------+
| 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(...)
和项目不进行分组。
你有没有相同的日期不同的百分比?或者你为什么要做.limit(1).first.percentage? – fanta 2015-03-02 18:43:56
是的,实际上它比这更复杂。我的问题是简单的版本。 – shankshera 2015-03-03 02:39:57