Difficulty with ActiveRecord query that does percentage calculation

。_饼干妹妹 提交于 2019-12-13 06:08:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!