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.
D9d1b31a337f46ac5e4dd56b55404f58?d=identicon&s=25 Dylan Markow (Guest)
on 2005-12-30 05:00
(Received via mailing list)
_______________________________________________
Rails mailing list
Rails@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails
Cee38055ae36590c654c04c2d5cc2778?d=identicon&s=25 Sky Yin (Guest)
on 2005-12-30 05: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 Markow <dylan@dylanmarkow.com> 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!
97a7959f0d9e6c90ddae200520e93067?d=identicon&s=25 Damon Clinkscales (Guest)
on 2005-12-30 06:54
(Received via mailing list)
Dylan Markow <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/
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2005-12-30 17:54
(Received via mailing list)
On 12/29/05, Dylan Markow <dylan@dylanmarkow.com> 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.