Rails 4 where,order,group,count include zero's - postgresql [英] Rails 4 where,order,group,count include zero's - postgresql

查看:176
本文介绍了Rails 4 where,order,group,count include zero's - postgresql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的查询:

User.where("created_at >= ? AND created_at <=?", date1,date2).order('DATE(created_at) DESC').group("DATE(created_at)").count  


b $ b

,我输出为:

and I get output as:

{Thu, 15 May 2014=>1}  

但是我想在剩下的天数输出为0。例如

But I want to get output as 0 for the rest of the days. For ex

{Thu, 15 May 2014=>1,Fri, 15 May 2014=>0}  

我想得到的是 Users code>日期范围,已排序分组 created_at 和每天的用户的编号。当没有用户在某个特定的日子,它应该返回0,当前的查询不返回。

What I want to get is Users created in a date range, ordered and grouped by created_at and number of such Users for each day. When no users are there for a particular day it should return 0, which the current query doesn't return.

推荐答案

我同意 Himesh

尝试:

User.where("created_at >= ? AND created_at <=?", date1,date2).order('DATE(created_at) DESC').group("DATE(created_at)").count  

其中:

{Thu, 15 May 2014=>1}  

获取哈希初始化为0的日期范围:

Get the date range as hash initialized to 0:

hash1 = Hash[(date1..date2).collect { |v| [v, 0] }]  



现在合并两个哈希:

Now merge the two hashes:

hash = hash1.merge(hash) 

请记住将 hash hash1 合并,而不是反之,因为我们要覆盖< $ hash1

Do remember to merge hash with hash1 and not the vice-versa, because we want to overwrite the value of keys from hash to hash1

这篇关于Rails 4 where,order,group,count include zero's - postgresql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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