0

My sql query is

SELECT MAX(sale_money)
FROM (
    SELECT SUM(sale_money) sale_money
    FROM sales
    WHERE MONTH(created_at) = 5
    GROUP BY user_id
) t

I write the subquery in Rails 4 code:

record = Sale.select("SUM(sale_money) AS sale_money").where("MONTH(created_at) = 5").group(:user_id)

Someone could teach me query the max_record based on record, or another query, except max_record = Sale.find_by_sql(my_raw_sql) or max_record = Sale.where(my_raw_sql)

0

1 Answer 1

1

Yes, the same can be done using Activerecord form method.

Sale.from(Sale.select("SUM(sale_money) AS sale_money")
               .where("MONTH(created_at) = 5")
               .group(:user_id), :t
         )
    .select("MAX(t.sale_money) as sale_money")

But, you can do as :

Sale.select("SUM(sale_money)")
    .where("MONTH(created_at) = 5")
    .group(:user_id)
    .order("SUM(sale_money) DESC")
    .limit(1)

The above one don't need the 2 SELECT queries.

Sign up to request clarification or add additional context in comments.

10 Comments

the 2nd query is working. The 1st one may be wrong. Rails parse wrong SQL query: SELECT sales.* FROM Sale.where("MONTH(created_at) = 5").select("SUM(sale_money) AS sale_money").group(:user_id). Thank you
Arup Rails understand 'Sale.select("SUM(sale_money) AS sale_money") .where("MONTH(created_at) = 5") .group(:user_id)' like a string. So, it parse your code to: SELECT MAX(t.sale_money) AS sale_money FROM Sale.select("SUM(sale_money) AS sale_money").where("MONTH(created_at) = 5").group(:user_id)
@user4557573 It is working here.. what you meant not working, I am not getting you..
Yes, I forgot removing the apostrophe ('...') in your first way. Thank for teaching me :)
Sorry for your time. And, I think you should update your 1st way with removing the apostrophe for other readers understand. I mean the 1st way should be Sale.from(Sale.select("SUM(sale_money) AS sale_money") .where("MONTH(created_at) = 5") .group(:user_id), :t ) .select("MAX(t.sale_money) as sale_money")
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.