【问题标题】:What are the equivalents of date() for month and hour?月份和小时的 date() 等价物是什么?
【发布时间】:2017-02-25 00:57:19
【问题描述】:

我正在使用 Ruby on rails 4.2 和 SQLite。

我知道我可以使用以下代码将记录按天分组created_at,然后将每个组的总数相加以返回每天总数的哈希:

Order.group("date(created_at)").select("created_at, sum(total) as total")

我想知道 Year, Month, Hour 是否有这个 date() 函数的等价物?

如果不是,我最好的分组记录选择是什么,而不使用 gems?

【问题讨论】:

    标签: ruby-on-rails sqlite ruby-on-rails-4 activerecord


    【解决方案1】:

    cast 是您正在寻找的 SQLite。

    Order.where("cast(strftime('%Y', created_at) as int) = ?", year)
    Order.where("cast(strftime('%m', date_column) as int) = ?", month)
    Order.where("cast(strftime('%d', date_column) as int) = ?", day_of_month)
    

    关于分组(EDIT):

    # group by year
    Order.group("strftime('%Y', created_at)").select("created_at, sum(total) as total")
    # group by month
    Order.group("strftime('%m', created_at)").select("created_at, sum(total) as total")
    # group by day
    Order.group("strftime('%d', created_at)").select("created_at, sum(total) as total")
    

    【讨论】:

    • error undefined local variable or method year' for main:Object`
    • @MoatazZaitoun 真的吗?也许你考虑用真正的整数(比如2016)而不是undefined local variable or method year? :)
    • 但是我不知道要按哪一年分组,我想按自己的分组每年的记录
    • 非常感谢,但被认为是一种好的做法-性能方面-?
    • @MoatazZaitoun 我从未见过将 sqlite 用作实际生产数据库。但至于性能——如果你使用 db 来做可以在 db 层上完成的事情——你可以确信这是一个很好的决定和一个很好的实践。因为用正确的工具做事不会错:)
    猜你喜欢
    • 2018-06-30
    • 2014-05-08
    • 2014-06-12
    • 1970-01-01
    • 2022-11-28
    • 2011-03-17
    • 2014-06-18
    • 2013-07-01
    • 1970-01-01
    相关资源
    最近更新 更多