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