Forum: Ruby on Rails Select SUM(?) Query

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dylan M. (Guest)
on 2005-12-30 06:00
(Received via mailing list)
_______________________________________________
Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails
Sky Y. (Guest)
on 2005-12-30 06:27
(Received via mailing list)
Make a quick test in Rails console, you will understand the result of
find_by_sql. Or, you can have a look at
Calculation<http://techno-weenie.net/blog/main/266/introducing....
Once installed, you can  use something like:

Order.calculate(:sum, :cost, :group => :country,
  :having => 'sum(cost) > 50')
# The document uses :group_by, but it should be :group

Easy enough?

On 12/29/05, Dylan M. <removed_email_address@domain.invalid> wrote:
>      When using PHP, I was able to enter a query against my list of
invoices such as :
>
>  Select SUM(amount) from invoices where project="123"
>
>  This would give me the total amount of all invoices for project 123.
>
>  In rails, how would I do this? I tried using "find_by_sql," but couldn't
figure out how to extract the results out of this. Thanks!
Damon C. (Guest)
on 2005-12-30 07:54
(Received via mailing list)
Dylan M. <dylan@...> writes:

> Select SUM(amount) from invoices where project="123"

Try:
  SELECT SUM(amount) as totalamount FROM invoices WHERE project="123"

In your result hash, grab the totalamount field.

-damon
http://damonclinkscales.com/
Wilson B. (Guest)
on 2005-12-30 18:54
(Received via mailing list)
On 12/29/05, Dylan M. <removed_email_address@domain.invalid> wrote:
>  When using PHP, I was able to enter a query against my list of invoices
> such as :
>
>  Select SUM(amount) from invoices where project="123"
>
>  This would give me the total amount of all invoices for project 123.
>
>  In rails, how would I do this? I tried using "find_by_sql," but couldn't
> figure out how to extract the results out of this. Thanks!
>
One way is:
Invoice.connection.select_value "select sum(amount) from invoices
where project_id = 123"
Unlike find_by_sql, this doesn't return an instance of 'Invoice'.. it
simply returns the value from the query, or nil if there were no
results

If you're expecting an integer as the result (e.g. count(*) from blah
where something), you can use Invoice.count_by_sql()
That would give you inaccurate results for 'amount', though, if
pennies are involved.
This topic is locked and can not be replied to.