mysql - Rails+ActiveRecords : How to group records by date and show their count based on a condition?

标签 mysql ruby-on-rails ruby activerecord group-by

我的数据库表中有这样的数据

ID | numbers | created_at
1  |   10    | 2016-04-01
2  |   20    | 2016-04-01 
3  |   -8    | 2016-04-01
4  |    1    | 2016-04-02
5  |   81    | 2016-04-03
6  |  -12    | 2016-04-03
7  |    0    | 2016-04-03

以及我想要得到的期望输出:

Date       | Greater (or even) than 0 | Smaller than 0
2016-04-01 | 2                        | 1 
2016-04-02 | 1                        | 0
2016-04-03 | 2                        | 1 

有没有一种方法可以从一个查询加载这些数据? 我能想到的只是我们的子查询以及在 Rails View 中执行查询,我想在其中呈现获取的数据。

最佳答案

我会尝试这样的事情:

lines = Model.
  select('date, SUM(IF(number > 0, 1, 0)) as greater_count', SUM(IF(number < 0, 1, 0)) as smaller_count').
  group(:date).
  order(:date)

lines.each do |line|
  puts [line.date, line.greater_count, line.smaller_count]
end

关于mysql - Rails+ActiveRecords : How to group records by date and show their count based on a condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387766/

相关文章:

ruby-on-rails - CircleCI 连接上的 Rails Fake-S3 被拒绝

ruby-on-rails - 如何在 ruby​​ on rails 中按日期对二维数组(2d 数组)进行排序?

python - 将 Ruby 移植到 Python

ruby - 帮助我为我的小脚本准备好选项

php - 多次mysql调用评论部分

mysql - 如何按时间对事件表进行排序(具有不同的时区)?

javascript - 如何使用promise.all使用mysql insert来级联样式?

ruby-on-rails - 在 Mavericks 上安装 Rails

mysql - 为什么 groovy withTransaction 不在 SqlException 上回滚?

ruby-on-rails - 上载csv文件时,我需要将错误从模型传递回 Controller