问题
I have a table with several hundred records, each one containing a datetime column. What is the most efficient way to find the distinct years from that datetime field?
回答1:
Using Ruby (this would require loading all the records, though):
Model.select("my_datetime").map{ |item| item.my_datetime.year }.uniq
Using SQL (this example is for PostgreSQL, I can update it with your specific database):
# PostgreSQL
Model.select("distinct(extract(year from my_datetime))")
# MySQL
Model.select("distinct(year(my_datetime))")
# SQLite
Model.select("strftime('%Y', my_datetime)")
回答2:
SELECT DISTINCT(YEAR(created_at)) FROM your_table
will probably work, but is heavily dependent of your used database (This will of course work with MySQL).
ActiveRecord
is a pain in the ass if you want using custom SQL statements, using Ruby statements like
Model.all.map(&:created_at).map(&:year).uniq
is indeed beautifuler, though it can be really slow because of loading and iterating over all your records.
回答3:
This will return the unique years in an array:
years = Model.pluck(:created_at).map{|x| x.year}.uniq
回答4:
This will return an array of years directly from the database in PostgreSQL:
YourModel.pluck("DISTINCT EXTRACT(YEAR FROM my_datetime)::Integer")
来源:https://stackoverflow.com/questions/6942986/how-to-find-distinct-years-from-a-table-with-multiple-years-in-rails