2011-09-16 134 views
1

我想计算每天命令要拍摄的员工数量。Ruby on rails积极记录多组记录来计算数字

Shoot.where("command_type = ?", "shoot").group("DATE(created_at)").group("employee_number").order("DATE(created_at)").count 

它会给我喜欢

{[Wed, 03 Aug 2011, "7838744451"]=>2, [Wed, 03 Aug 2011, "8055898284"]=>11,[Fri, 05 Aug 2011, "9702553828"]=>1, [Fri, 05 Aug 2011, "9717466677"]=>1,[Fri, 05 Aug 2011, "8055898284"]=>1,[Wed, 06 Aug 2011, "8055898284"]=>5 

我想有一个数组像一个输出: -

[2,0,3,1] // zero is for the dates when no record is there for that date. and number in the array is that number of the employees that has been ordered to shoot. 

例如从数组:2的员工被勒令拍摄上周三,3日 0名员工被命令第4次拍摄,依此类推......

另外:我如何计算,所有员工被命令在一周/一个月内拍摄多少次。基本上有100名员工被命令第一周开枪。 120名员工为了第2周拍摄第1个月和第2个月等。

+0

这听起来像一个有趣的项目... – sscirrus

+0

谁低估了我?任何1可以告诉我最新的问题。这是一个糟糕的问题,或者这是提问的不好方法..请留下评论。 –

+0

@sscrirrus项目的意义在哪里? –

回答

1

您正在使用的命令返回员工的每日计数。如果您想要获得员工的每日点击次数,请删除第二个group电话。

# return [2,3,1] 
Shoot.where(:command_type => shoot").group("DATE(created_at)").values 

如果你想以填补缺失的日期值,您可以使用此功能:

class Shoot 
    def self.daily_count_by_type(type = "shoot", range=7.days) 
    counts = Shoot.where(:command_type => type).group("DATE(created_at)"). 
       count("DISTINCT employee_id") 
    (range.ago.to_date..Date.today).map {|d| counts[d.to_s] || 0} 
    end 
end 

现在

Shoot.daily_count_by_type # for type `shoot`, last 7 days 
Shoot.daily_count_by_type("shoot") # for type `shoot`, last 7 days 
Shoot.daily_count_by_type("eat", 14.days) # for type `eat`, last 14 days 
Shoot.daily_count_by_type("leave") # for type `leave`, last 14 days 

确保您在DATE(CREATED_AT)添加一个索引来提高性能。

编辑根据您需要统计不同值的注释1

。我已经相应地更新了答案。

+0

事情是一名员工可以命令在同一天拍摄两次或三次。所以我想把它算作一个。 –

+0

根据评论你需要计算不同的值。我已经相应地更新了答案。 –