2

我想绘制一个图表来查看过去 30 天的用户增长情况。

所以它将是一个像这样的数组:(一个增量数组)

 [0,100,250,500,1000,1100.....5000,5500]

解决方案 1:一个愚蠢的方法是每天触发查询:

  (30.days.ago.to_date..Date.today).map {|date| User.where("Date(created_at) <= ?" , date).count}

但这将触发 30 个查询。

解决方案 2:使用 group by 选项查找所有记录,然后对其进行循环并总结以前的记录。

 User.group('Date(created_at)').count
 (30.days.ago.to_date..Date.today).map {|date| counts[date] || 0} //and again loop over it
 //and now start summing up previous ones elements to get an another array..

但是这两种解决方案都是无用的。将其作为优化建议的任何建议。

4

2 回答 2

0

You should be able to do this with sql itself,

Ex: I have the following table

+---------+---------------------+
| user_id | training_start_date |
+---------+---------------------+
|   15981 | 2012-10-08 06:12:45 |
|   15981 | 2012-10-08 06:13:26 |
|   15981 | 2012-10-08 06:29:34 |
|   15981 | 2012-10-08 06:33:53 |
| 1005933 | 2012-10-08 07:41:54 |
+---------+---------------------+

when I want to get how many users got the training each day, I could do

select count(user_id), training_start_date from training_users group by DATE_FORMAT(training_start_date, "%M %e, %Y");

This is the link which helped me

HTH

于 2012-11-28T21:36:31.983 回答
0

我将执行以下操作:

growth = []
users =  User.group('Date(created_at)').count

(30.days.ago.to_date..Date.today).each do |day|
  growth.push(growth.sum + (users[day] || 0))
end

未经测试,但你明白了。

于 2012-11-28T22:32:46.420 回答