0

The following code below works as a Postgre query, i'm trying to call it inside my rails app and assigning it to an object: @agent_monthly_performance.

SELECT user_id AS user_id,
       to_char(created_at,'Mon-YY') AS year_month,
       sum(total_amount) AS amount,
       sum(total_lm) AS lm
FROM   agent_sales
WHERE  created_at > NOW() - INTERVAL '1 year'
GROUP BY user_id, year_month"

Once that works, will I be able to call it via @agent_monthly_performance.year_month? I'm aware that i've created new columns that aren't in my schema via "AS" command. (ex. year_month).

3 Answers 3

3

MyModel.find_by_sql(query) will still inherit model instance. You might need to check it further

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

1 Comment

This works but only for user_id, the attribute available in my table. Is there a way to output my three other SELECT requirements?
1

you can use ActiveRecord::Base.connection.execute to execute row sql queries in rails

@agent_monthly_performance = ActiveRecord::Base.connection.execute("SELECT user_id AS user_id, to_char(created_at,'Mon-YY') AS year_month, sum(total_amount) AS amount, sum(total_lm) AS lm FROM   agent_sales WHERE  created_at > NOW() - INTERVAL '1 year' GROUP BY user_id, year_month").to_a

2 Comments

Your answer outputs this: => #<PG::Result:0x007fb3755e0030 status=PGRES_TUPLES_OK ntuples=3 nfields=4 cmd_tuples=3> Not really sure how to access that.
you just need to add .to_a at the end. I update the answer.
0

You could do this:

sql = <<-SQL
  SELECT user_id AS user_id,
       to_char(created_at,'Mon-YY') AS year_month,
       sum(total_amount) AS amount,
       sum(total_lm) AS lm
  FROM   agent_sales
  WHERE  created_at > NOW() - INTERVAL '1 year'
  GROUP BY user_id, year_month
SQL

SomeModel.find_by_sql(sql)

4 Comments

I tried doing this to my model: AgentSale. It doesn't produce an error but the output is: [#<AgentSale id: nil, user_id: 14>, #<AgentSale id: nil, user_id: 13>, #<AgentSale id: nil, user_id: 1>] It seems to only select the attributes that is in the model. What about the 3 other entries in my SELECT that has some computations to it, how can I get that to output?
Looks like you need to add another table to your FROM statement. Currently you're only pulling from agent_sales, which I'm guessing is only a join table.
All my data is in agent_sales, do you mean I need to add another agent_sales table and join them together?
Not necessarily. I didn't see that you were adding 'columns' with an AS statement.

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.