我如何在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)
答案 0 :(得分:0)
最简单的是:
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
中都有很好的描述答案 1 :(得分:0)
我使用这种方法:
sql =“ SELECT MONTH(created_at)为'mês',sum(points)为'total de pontos',count(*)为'operações',avg(points)为'média',avg(cost)as 'customédio',avg(cost)*(sum(points)/ 10000)as'gasto total'FROM operation其中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