【问题标题】:SQLite: group records by month they were created and get a count of records per monthSQLite:按创建记录的月份对记录进行分组,并获取每月记录的计数
【发布时间】:2014-12-26 11:12:16
【问题描述】:

我知道,我知道有几个非常相似的问题,但他们处理 Postgres 和 MySQL。

我有一个跟踪页面访问的模型(事件),我想分组然后计算每月创建的事件,并使用 Chart.js 显示它。但我不知道如何查询 SQLite 以收集在某个月份创建的事件。

SQLite 无法处理EXTRACT(),或类似Model.where("MONTH(created_at) = ?", 9)

我也试过这个question建议的Event.where("strftime('%-m', created_at) = ?", 9),但没有运气。无论我尝试什么月份,它都会返回0

作为一个老手,我什至尝试在事件中添加一个month 列,用created_at.month 填充它,但后来放弃了那个分支。

我是 Rails 开发的新手,对查询感到不安,但我查看了以下问题,仍然无法拼凑出任何东西: How to make a query in Postgres to group records by month they were created? (:created_at datetime column)Selecting by month in PostgreSQLGetting count of elements by `created_at` by day in a given monthGroup records by both month and year in RailsUse active record to find a record by month and day, ignoring year and time

【问题讨论】:

标签: ruby-on-rails sqlite querying


【解决方案1】:

strftime 的正确替换是 %m,而不是 %-m

此外,strftime 返回一个零填充字符串:

.where("strftime('%m', created_at) = ?", "09")

【讨论】:

  • 是的,这就是我这样做的原因%-m,这样它就不会被零填充。即使只有%m,我也会得到相同的输出。
【解决方案2】:

我的 Bloc.io 导师引导我这样做:http://railscasts.com/episodes/29-group-by-month

所以我可以做这样的事情来返回一个以月份为键的哈希:

months = Event.all.group_by { |t| t.created_at.beginning_of_month }

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多