问题
I have an ActiveRecord schema, PurchaseSummary, that I inherited and THAT I CAN NOT CHANGE that looks like this:
purchase_summaries
date date_of_purchase
integer number_of_purchases
boolean coupon_used
example, for November 1st, there were 800 purchases, 500 without a coupon, 300 with a coupon, and on Nov 2nd, 600 purchases without a coupon, and 100 with, so the rows in the database look like this:
2011-11-01, 500, false
2011-11-01, 300, true
2011-11-02, 600, false
2011-11-02, 100, true
In example, total number of purchases for 11/1 are 800 and 11/2 700.
The problem: I would like to construct a query that returns for each day, the percentage of purchases that used a coupon, or
2011-11-01, 0.375
2011-11-02, 0.142
回答1:
Not th most optimized way, but you can do something like :
select date_of_purchase
,sum(number_of_purchases) / (select sum(subquery.number_of_purchases)
from purchase_summaries subquery
where subquery.date_of_purchase = query.date_of_purchase
and subquery.coupon_used = 1) * 100 as percentage
from purchase_summaries query
group by date_of_purchase
来源:https://stackoverflow.com/questions/8248596/difficulty-with-activerecord-query-that-does-percentage-calculation