Rails / ActiveRecord按月和年分组并计数 [英] Rails/ActiveRecord Group by month+year with counts
问题描述
我有一张相册
的表,其中有一个 date
列,名为 release_date
。
I have a table of Albums
that has a date
column named release_date
.
我想获取所有存在的月份和年份组合的列表,以及该月份/年份发行的专辑数量。
I want to get a list of all the month + year combinations present along with the number of albums released in that month/year.
因此,输出可能类似于:
So, the output might be something like:
- 2016年11月-11
- 2016年10月-4
- 2016年7月-19
- 2015年12月-2
- November 2016 - 11
- October 2016 - 4
- July 2016 - 19
- December 2015 - 2
Ruby 2.3.1 w / Rails 5 on Postgres 9.6,FWIW。
Ruby 2.3.1 w/ Rails 5 on Postgres 9.6, FWIW.
推荐答案
我假设您的表按照Rails约定是单个相册
。
I'm assuming your table is singular Album
per Rails convention. If not, consider changing it.
Album.all.map { |album| [Date::MONTHNAMES[album.date.month], album.date.year].join(' ') }
.each_with_object(Hash.new(0)) { |month_year, counts| counts[month_year] += 1 }
说明:
.map
方法遍历相册并返回由 [ month year, month year, ...]
。
The .map
method iterates over the albums and returns an array of strings consisting of ["month year", "month year", ... ]
.
.each_with_object
方法是一种标准计数算法,可为每个唯一数组项返回带有计数的哈希。
The .each_with_object
method is a standard counting algorithm that returns a hash with a count for each unique array item.
这篇关于Rails / ActiveRecord按月和年分组并计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!