Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 按天和小时分组并计数-如果没有,则输出0_Mysql_Sql_Ruby On Rails - Fatal编程技术网

Mysql 按天和小时分组并计数-如果没有,则输出0

Mysql 按天和小时分组并计数-如果没有,则输出0,mysql,sql,ruby-on-rails,Mysql,Sql,Ruby On Rails,如果我这样做的话 TrackMood.where(mood: "good").group("date_format(created_at, '%Y%m%d %H')").count 它生成sql SELECT COUNT(*) AS count_all, date_format(created_at, '%Y%m%d %H') AS date_format_created_at_y_m_d_h FROM `track_moods` WHERE `track_moods`.`mood` =

如果我这样做的话

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

SELECT COUNT(*) AS count_all, date_format(created_at, '%Y%m%d %H') 
AS date_format_created_at_y_m_d_h
FROM `track_moods` 
WHERE `track_moods`.`mood` = 'good' GROUP BY date_format(created_at, '%Y%m%d %H')
我得到一个散列作为输出

{"20120524 11"=>10, "20120524 12"=>7, "20120524 13"=>15}
我想在没有创建记录的小时数的散列中得到零

我已尝试创建一个包含我要检查的所有小时数的数组:

times = ((Time.now - 5.days).to_i..Time.now.to_i).to_a.in_groups_of(1.hour)
         .collect(&:first).collect { |t| Time.at(t).strftime('%Y%m%d %H') }
然后尝试

TrackMood.where("mood = 'good' AND date_format(updated_at, '%Y%m%d %H')
IN (:times)", mood: "good", site_id: 2, times: times )
.group("date_format(created_at, '%Y%m%d %H')").count
但这仍然给了我和以前一样的哈希值

那么,如何将零添加到散列中呢


我使用的是MYSQL数据库。

为什么要担心添加零?如果哈希中不存在所需的小时数,为什么不假定一个隐式的零呢?节省大量内存!我想把这些值传递给一个图,所以如果它们不存在的话,就需要添加零。我认为在数据库层添加它们会更有效率。在MySQL中不容易做到这一点-需要外部连接一个临时或内联表,其中包含所有所需的小时数。这样的任务通常在应用程序中更容易完成。很公平,我可以在rails中轻松完成。谢谢你的意见。