views:

47

answers:

3

Hello, i have a really complex query (mysql + php) and i would like to know the easiest way to sum columns and rows of a table apart from using SUM(x).

Maybe a javascript could help. Thanks in advance.

A: 

I would do this in the query itself. If you post the query, I can provide more information.

RedFilter
A: 

This is the query, i want to sum cols and rows. ( rows are the vars "svago" and "lavoro" ordered for each month of the year, while cols are the same values in the whole year )

$q = "SELECT DISTINCT DATE_FORMAT( TIMESTAMP,  '%m%Y' ) AS derp FROM main LIMIT 0 , 30";
$qq = mysql_query($q);

while($res = mysql_fetch_array($qq)) {

$where = $res['derp'];

$q = "SELECT timestamp, SUM(moto) + SUM(mary) AS svago, SUM(lavoro) + SUM(affitto) AS lavoro FROM main WHERE DATE_FORMAT(timestamp, '%m%Y') = $where";
Ldx
A: 

I would advise to use the SUM() function in MySQL. The only reason to not use it is if you have some complicated counting based on other values. Then I would do the counting in the PHP. Here is an example:

$result = mysql_query("... query here ...");
$cats = 0;
$dogs = 0;
while($row = mysql_fetch_array($result))
{
     if($row['type'] == 'cat')
     {
          $cats++;
     }
     else
     {
          $dogs++;
     }
 }
echo "Cats: $cats Dogs: $dogs";
Justin Carmony