Pad总结结果为0

时间:2013-06-28 20:59:46

标签: ruby-on-rails algorithm rails-postgresql

我有一个rails 4(ruby 2)应用程序,可以跟踪员工对各个公司的时间。我需要得到每个公司每个日期的分钟数。我的问题是,如果当天该公司没有时间条目,我不确定将日期/公司对填0的最佳方法。

表格

Companies      Time_Entries
id name ...    id, created_at, company_id, minutes ...

当前输出仅给出2家公司和2天,

[{"company_id":1,"company_name":"Company A","date":"2013-06-24","minutes":987},
 {"company_id":1,"company_name":"Company A","date":"2013-06-25","minutes":5},
 {"company_id":2,"company_name":"Company B","date":"2013-06-24","minutes":500}]

预期输出要做的是没有记录0的填充天数是在列表中有一个额外的项目,其中最后一项是新项目。

[{"company_id":1,"company_name":"Company A","date":"2013-06-24","minutes":987},
 {"company_id":1,"company_name":"Company A","date":"2013-06-25","minutes":5},
 {"company_id":2,"company_name":"Company B","date":"2013-06-24","minutes":500},
 {"company_id":2,"company_name":"Company B","date":"2013-06-25","minutes":0}]

当前查询(PostgreSQL)

 @minutes = TimeEntry.where("created_at >= ?", 1.week.ago.utc)
  .group('companies.id, date(created_at)')
  .joins(:company)
  .select("companies.id as company_id", "companies.name as company_name", "date(created_at)", "SUM(minutes) as minutes")
  .order("date ASC")

我不确定最好的办法。我可以想到几个选项:

  • 一个循环数天的循环,而不是循环通过公司,而不是循环查找结果,以添加尚未添加的任何日/公司对。
  • generate_series()上为postgresq中的日期范围进行左连接,并将null sums合并为0,但我认为这不会让我一路走来
  • 一些未知的更优雅的选择

0 个答案:

没有答案