简体   繁体   English

Rails + ActiveRecords:如何按日期对记录进行分组并根据条件显示其计数?

[英]Rails+ActiveRecords: How to group records by date and show their count based on a condition?

I have data like this in a DB table 我在数据库表中有这样的数据

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

And the desired output I'd like to get: 和我想要得到的期望的输出:

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

Is there a way to load this data from one query? 有没有一种方法可以从一个查询加载此数据? All I can think of our subqueries and doing queries in the Rails view where I want to render the fetched data. 我所能想到的所有子查询和在Rails视图中进行查询的位置,都希望在其中呈现所获取的数据。

I would try something like this: 我会尝试这样的事情:

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

Assuming your Created_at is a date with no time components... similar to spickermann's but less platform specific. 假设您的Created_at是一个没有时间成分的日期,类似于spickermann的日期,但平台特定性较低。

Select Created_at as Date
     , Sum(case WHEN numbers >= 0 THEN 1 Else 0 END) as GTE_0
     , Sum(case WHEN numbers < 0 THEN 1 Else 0 END) as LT_0
FROM Table
GROUP BY Created_at

What this does is evaluate the number if >=0 then it sets a value of 1 which it then sums by date for Greater than Equal to 0 (GTE_0) Similar done for LT_0 (Less than 0). 如果> = 0,它将计算数字,然后将其设置为1,然后按日期求和,得出大于等于0(GTE_0)的值,与LT_0(小于0)相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM