平均每小时间隔 - Rails
Average per hour inverval - Rails
[信息:Ubuntu 14.02,ruby 2.2.3p110,Rails 4.2.1]
我需要一个 rake 任务来从数据库(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 获得这个每小时的平均值?
您可以使用嵌套的原始 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
子查询中)
- 平均每小时计数(在外部查询中)
我使用 answer:
的查询解决了我的问题
我编辑了 table 名称,删除了 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
[信息:Ubuntu 14.02,ruby 2.2.3p110,Rails 4.2.1]
我需要一个 rake 任务来从数据库(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 获得这个每小时的平均值?
您可以使用嵌套的原始 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
子查询中) - 平均每小时计数(在外部查询中)
我使用 answer:
的查询解决了我的问题
我编辑了 table 名称,删除了 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