Note that there are some explanatory texts on larger screens.

plurals
  1. POTricky Rails3/mysql query
    primarykey
    data
    text
    <p>In rails 3 (also with meta_where gem if you feel like using it in your query), I got a really tricky query that I have been banging my head for:</p> <p>Suppose I have two models, customers and purchases, customer have many purchases. Let's define customers with at least 2 purchases as "repeat_customer". I need to find the total number of repeat_customers by each day for the past 3 months, something like:</p> <pre><code>Date TotalRepeatCustomerCount 1/1/11 10 (10 repeat customers by the end of 1/1/11) 1/2/11 15 (5 more customer gained "repeat" status on this date) 1/3/11 16 (1 more customer gained "repeat" status on this date) ... 3/30/11 150 3/31/11 160 </code></pre> <p>Basically I need to group customer count based on the date of creation of their second purchase, since that is when they "gain repeat status". </p> <p>Certainly this can be achieved in ruby, something like:</p> <pre><code>Customer.includes(:purchases).all.select{|x| x.purchases.count &gt;= 2 }.group_by{|x| x.purchases.second.created_at.to_date }.map{|date, customers| [date, customers.count]} </code></pre> <p>However, the above code will fire query on the same lines of <code>Customer.all</code> and <code>Purchase.all</code>, then do a bunch of calculation in ruby. I would much prefer doing selection, grouping and calculations in mysql, since it is not only much faster, it also reduces the bandwith from the database. In large databases, the code above is basically useless. </p> <p>I have been trying for a while to conjure up the query in rails/active_record, but have no luck even with the nice meta_where gem. If I have to, I will accept a solution in pure mysql query as well. </p> <p>Edited: I would cache it (or add a "repeat" field to customers), though only for this simplified problem. The criteria for repeat customer can change by the client at any point (2 purchases, 3 purchases, 4 purchases etc), so unfortunately I do have to calculate it on the spot.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload