2011-09-16 128 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

根據評論你需要計算不同的值。我已經相應地更新了答案。 –