我想绘制图表以查看过去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:使用分组选项查找所有记录,然后对其进行循环并汇总以前的记录。
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..
但两种解决方案都没用。任何建议,使其成为优化的。
答案 0 :(得分:0)
你应该能够用sql本身做到这一点,
例如:我有下表
+---------+---------------------+
| 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 |
+---------+---------------------+
当我想知道每天有多少用户接受培训时,我可以做到
select count(user_id), training_start_date from training_users group by DATE_FORMAT(training_start_date, "%M %e, %Y");
的链接
HTH
答案 1 :(得分: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
未经测试,但您明白了。