[信息:Ubuntu 14.02,ruby 2.2.3p110,Rails 4.2.1]
我需要一个rake任务来从DB(SQLite)中获取每小时范围的平均插入次数[如00:00到00:59]。
我试图做一些像:
namespace :db do
task results: :environment do
tweet = Tweet.group('date(created_at)').group('hour(created_at)').average()
puts "#{tweet}"
end
end
但这让我这个例外
ActiveRecord::StatementInvalid: SQLite3::SQLException: misuse of aggregate function count(): SELECT AVG(count(*)) AS average_count_all, date(created_at) AS date_created_at, hour(created_at) AS hour_created_at FROM "tweet" GROUP BY date(created_at), hour(created_at)
有没有办法使用ActiveRecord获得每小时的平均值?
答案 0 :(得分:1)
您可以使用嵌套的原始SQL查询:
SELECT
AVG(hourly_count) as average_count_all
FROM
(
SELECT
count(*) as hourly_count,
date_created_at,
hour_created_at
FROM
(
SELECT
date(created_at) as date_created_at,
hour(created_at) as hour_created_at
FROM
tweet
) as hours
GROUP BY
date_created_at,
hour_created_at
) as hourly_counts
这是未经测试的,但这个想法是这样的:
hours
子查询中)hourly_counts
子查询中)答案 1 :(得分:0)
我使用此answer的查询解决了我的问题:
我编辑了表名,删除了where子句,将date(from_unixtime('date'))
更改为date(created_at)
并将hour(from_unixtime('date'))
更改为strftime('%H', created_at)
(SQLite没有hour()
函数)
所以我有类似的东西:
select the_hour,avg(the_count) from(
select date(created_at) as the_day, strftime('%H', created_at) as the_hour, count(*) as the_count
from tweet group by the_day,the_hour
) s group by the_hour