轨道 - 一天一天以及一小时 [英] rails - group by day as well as hour

查看:99
本文介绍了轨道 - 一天一天以及一小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在跟踪人们的感受,所以我的模型叫做 TrackMood 它只有一个名为心情的列和时间戳。



如果我做

  TrackMood.where(心情:好)。group(hour(created_at)) $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $,$,,,,,,,,,,,,,,,,,,,,,,, 13 => 2,15 => 1} 



我在这里有2个问题



1如何我把这一天添加到这里,所以它不只是添加昨天在11点钟创建的项目今天在11点添加的项目?



2如何

解决方案

p> 1)而不是仅在日期的几个小时内分组,您需要将相关日期的一部分即日期直至小时,而不包括任何更具体的日期一个例如。

  TrackMood.where(心情:好)group(date_format(created_at,'%Y%m%d% H'))。count 

2)你总是从这里得到一个哈希即使没有找到任何组也可以打电话。如果您想查看有多少组,您可以在其上调用 .size .count


I want to create an array of the number of items created each hour, each day.

I'm tracking how people are feeling, so my model is called TrackMood It just has a column called mood and the timestamps.

If I do

TrackMood.where(mood: "good").group("hour(created_at)").count

I get something like {11=>4, 12=>2, 13=>2, 15=>1}

I've got 2 issues here

1 How do I add the day into this so it doesn't just add the items created yesterday at 11 o'clock to the items added today at 11 o'clock?

2 How do I make sure it says 0 for hours when nothing is created?

解决方案

1) Instead of grouping on just the hours part of the date you'll need to group part of the date that is relevant i.e. the date up to the hours and not including anything more specific than that. E.g.

TrackMood.where(mood: "good").group("date_format(created_at, '%Y%m%d %H')").count

2) You're always going to get a hash back from this call even if it doesn't find any groups. If you want to check how many groups there are you can call .size or .count on it.

这篇关于轨道 - 一天一天以及一小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆