如何在Rails中从具有多年的表格中查找不同的年份 [英] How to find distinct years from a table with multiple years in Rails

查看:54
本文介绍了如何在Rails中从具有多年的表格中查找不同的年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数百条记录的表,每个记录包含一个datetime列。从该日期时间字段查找不同年份的最有效方法是什么?

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?

推荐答案

使用Ruby(这需要加载所有记录,但):

Using Ruby (this would require loading all the records, though):

Model.select("my_datetime").map{ |item| item.my_datetime.year }.uniq

使用SQL(此示例适用于PostgreSQL,我可以对其进行更新与您的特定数据库):

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)")

这篇关于如何在Rails中从具有多年的表格中查找不同的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆