Page 1 of 1

What is easiest way to add up all values returned by query?

Posted: Wed Apr 02, 2003 1:09 am
by 3dron
How can I get the sum of all the values in a column returned by my query?

$query['data'];

How do I add up all the values? In the column "data"?

I can think of doing it in a loop while mysql_fetch_assoc.

Or by grabbing mysql_num_rows and going through the array one value at a time.

But is there a simpler/cleaner way of doing it all?

Thanks

Ron

Posted: Wed Apr 02, 2003 2:12 am
by bionicdonkey
you can do it within the query..i think it's something like:

Code: Select all

SELECT SUM(tablename.fieldname) AS whatever
FROM tablename
GROUP BY fieldname;

Posted: Wed Apr 02, 2003 2:56 am
by d1223m
do you need the "group by" for that?

are you getting it confused with :

select count(fieldname) from tablename group by fieldname

just curious :)

Posted: Wed Apr 02, 2003 3:39 am
by Bitmaster

Code: Select all

select count(fieldname) from tablename where ...
That query will return the NUMBER of rows that match a specific 'where' clause.

The query with the SUM (...) statement will return the sum of all columns. I don't know the exact mySQL syntax for it, but it will take you in the right direction

Posted: Wed Apr 02, 2003 4:30 pm
by bionicdonkey
i'm preety sure SUM() comes under the GROUP BY clause

Posted: Thu Apr 03, 2003 1:11 am
by twigletmac
bionicdonkey wrote:i'm preety sure SUM() comes under the GROUP BY clause
Which is why info about it is located here:
http://www.mysql.com/doc/en/Group_by_functions.html

Mac