Click to See Complete Forum and Search --> : sum of all mysql columns


ifm1989
12-22-2007, 01:56 AM
Just wondering if there was something in MYSQL that gets the sum of all rows? Something like this:

SELECT sum(*) as * FROM

It's annoying to have to write out every column by hand.

Amaroq
12-24-2007, 03:26 PM
I assume all the rows in the column are numerical, of course.

Just run a query that returns all the rows as an array, make sure PHP is treating them like numbers, and then use array_sum() to return the sum of every element in the array.

Unless you just want to know how many rows there are. I think there might be a query that returns that. Or even a PHP mysql/mysqli function that will return how many rows or columns are in that result pointer.

jishua
08-19-2008, 10:59 AM
For those interested here's one way, specifically, with php:

$pre_query = SELECT * FROM example; //to get field names
$result = mysql_query($pre_query) or die(mysql_error());

$query = "SELECT *,";
for($i = 0; $i < mysql_num_fields($result); $i++) {
if ($i == (mysql_num_fields($result)-1))
$query .= "SUM(".mysql_field_name($result,$i).")";
else
$query .= "SUM(".mysql_field_name($result,$i)."), ";
}
$query .= " FROM example GROUP BY something";


(where example is the table name and something is a grouping--I think mandatory)