我有一个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,但我认为这不会让我一路走来