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

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
3dron
Forum Commoner
Posts: 40
Joined: Sat Feb 01, 2003 10:25 pm

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

Post 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
bionicdonkey
Forum Contributor
Posts: 132
Joined: Fri Jan 31, 2003 2:28 am
Location: Sydney, Australia
Contact:

Post 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;
User avatar
d1223m
Forum Commoner
Posts: 80
Joined: Mon Mar 31, 2003 5:15 am
Location: UK, West Sussex

Post 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 :)
Bitmaster
Forum Newbie
Posts: 20
Joined: Thu Nov 21, 2002 8:42 am

Post 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
bionicdonkey
Forum Contributor
Posts: 132
Joined: Fri Jan 31, 2003 2:28 am
Location: Sydney, Australia
Contact:

Post by bionicdonkey »

i'm preety sure SUM() comes under the GROUP BY clause
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
Post Reply