sql - Rails 按 :created_at, 返回 :status column, 的计数对表进行分组,然后使用每个唯一值的计数对 :status 列进行子分组

标签 sql ruby-on-rails ruby activerecord

我有一个通知模型,我想知道每天创建了多少通知以及每个状态有多少通知。 status 是模型 Notification 的字符串键。

Notification.where(user: users).group('DATE(created_at)').count('created_at')

那给我:

{Mon, 05 Oct 2015=>2572,
 Tue, 06 Oct 2015=>555,
 Wed, 07 Oct 2015=>2124,
 Thu, 08 Oct 2015=>220,
 Fri, 09 Oct 2015=>36}

但是我想要这样的东西:

{Mon, 05 Oct 2015=>{total=>2572, error=>500, pending=>12},
 Tue, 06 Oct 2015=>{total=>555, sent=>50, pending=>12}}

或类似的。事件记录有可能吗?也许group_by对我有好处。但它已被弃用。

目前我已经尝试过:

Notification.where(user: users).group('DATE(created_at), status').count('created_at') 
# => {"error"=>2, "sent"=>42}

这不是我想要的结果。

最佳答案

这对我来说很难测试可能的答案,因为日期有点独特而且查询有点复杂。但这里是如何在哈希中获取计数:

my_hash = {} #create your empty hash
notifications = Notification.where(user: users).select(:created_at).uniq
  #get a hash of Notification objects with unique created_at dates
notifications.each do |n|
  my_hash[n.created_at] = Notification.where(created_at: n.created_at).select(:status).group(:status).count
  #load your hash with <created_at date> => {"error" => 20, "pending" => 30}
  my_hash[n.created_at]["total"] = Notification.where(created_at: n.created_at).count
  #add the total count to your hash
end

编辑

正如 OP 发现的那样,随着查询日期数量的增加,这变得非常低效。那是因为它正在为第一个查询中返回的每个日期调用一个查询。我确信有一种方法可以将此作为一个长 SQL 查询来执行,并将其用作数据库中的 View 。

关于sql - Rails 按 :created_at, 返回 :status column, 的计数对表进行分组,然后使用每个唯一值的计数对 :status 列进行子分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34205836/

相关文章:

java - 如何使用同一个 Java 类来执行不同的 SQL 查询

ruby-on-rails - ruby on rails 3.0 TimeWithZone 添加时间无法强制进入 Fixnum

ruby-on-rails - Rails事件记录重复并保存失败

ruby-on-rails - Rake 命令中止/Ruby Rails

ruby - rbenv ruby​​ 安装失败 ubuntu

ruby-on-rails - Ruby 使用数据库属性总和更新属性

mysql - 在同一张表上使用左连接的成员(member)更新报告

sql - 如何从 1 个表中选择多行并插入到另一个表中特定行的特定 JSONB 字段中?但在单个原始 SQL 查询中

sql - 匹配多个字段组合的记录

javascript - 如何从 Ruby on Rails 应用程序将参数从根 html 元素传递到 ReactJS