【问题标题】:Translate sql query to ActiveRecord Query将 sql 查询转换为 ActiveRecord 查询
【发布时间】:2018-10-16 19:00:05
【问题描述】:

我如何在 rails 终端上写这个查询?

select
    month(created_at) as 'mês',
    sum(points) as 'total de pontos',
    count(*) as 'operações',
    avg(points) as 'média'
from
    cashmilhas_07_16.operations
where
    operation_type = 1
    and created_at >= '2018-01-01'
group by
    year(created_at),
    month(created_at)

【问题讨论】:

标签: sql ruby-on-rails activerecord


【解决方案1】:

最简单的是:

Operation.find_by_sql [
  'select
      month(created_at) as "mês",
      sum(points) as "total de pontos",
      count(*) as "operações",
      avg(points) as "média"
    from cashmilhas_07_16.operations
    where operation_type = :type and created_at >= :date
    group by year(created_at), month(created_at)',
  { type: 1, date: '2018-01-01' }
]

或者:

Operation.where("operation_type = :type and created_at >= :date", { type: 1, date: '2018-01-01' })
         .select('month(created_at) as "mês", sum(points) as "total de pontos", count(*) as "operações", avg(points) as "média"')
         .group("year(created_at), month(created_at)")

Rails API 中对这两种方法都有很好的描述

【讨论】:

  • 返回是空的,但是如果我输入这个查询: Operation.where("operation_type = :type and created_at >= :date", { type: 1, date: '2018-01-01' }).count 有回报
  • 第一次查询呢?
  • 对不起,但我认为您的原始查询返回空结果。尝试在数据库控制台中运行该查询(无论您使用什么,mysql 或 postgres)
【解决方案2】:

我用这个方法:

sql = "SELECT MONTH(created_at) as 'mês', sum(points) as 'total de pontos',count(*) as 'operações', avg(points) as 'média', avg(cost) as 'custo médio', avg(cost) * (sum(points)/10000) as 'gasto total' FROM operations where operation_type = 2 AND source_target_id = 1 AND created_at >= '2018-01-01' GROUP BY YEAR(created_at) , MONTH(created_at);"

结果 = ActiveRecord::Base.connection.exec_query(sql)

results.rows

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多