我有以下 mysql 查询运行良好。快速背景故事,这按总支出列出了我们的客户。
SELECT SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary
FROM customer_order AS co
JOIN customer AS cu ON (cu.customer_id = co.customer_id)
GROUP BY co.customer_id
ORDER BY money_spent DESC
我尝试将其作为范围和子类移至客户模型,但两种方式都失败了。我对 Rails(以前是客户端)有点陌生,但我想我已经很接近了。希望你们能指出我正确的方向。提前致谢!!!
def self.high_rollers
options = {
:select => "SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary",
:from => "customer_order AS co",
:joins => "customer AS cu ON (cu.customer_id = co.customer_id)",
:group_by => "co.customer_id",
:order => "money_spent DESC"
}
将以下代码放入此控制器的索引操作中是可行的,但绝对不是正确的方法!
@high_bidders = Customer.find_by_sql(<<-SQL
SELECT SUM(price) AS money_spent, co.customer_id, cu.first_name, cu.last_name, cu.email_primary
FROM customer_order AS co
JOIN customer AS cu ON (cu.customer_id = co.customer_id)
GROUP BY co.customer_id
ORDER BY money_spent DESC
SQL)