user1371500
user1371500

Reputation: 93

Sum SQL Fields Together For total result

I am trying to Sum a number of fields within a SQL Database. The fields are called week1 to week 13 as they store results for each week. I have this at the moment however it is not outputting anything, any help would be appreciated. Cheers

<?php
            if ($resultsRows == 0){
            echo '<p> No results have been listed for you yet. </p>';
            }
            if ($resultsRows > 0){              
            $qrytotalresult = "SELECT SUM(week1 + week2 + week3 + week4 + week5 + week6 + week7 + week8 + week9 + week10 + week11 + week12 + week13) FROM results WHERE username = '$username'";
            $TotalResult = mysql_query($qrytotalresult);
            return $TotalResult;

            }
        ?>

Upvotes: 1

Views: 204

Answers (3)

ejb_guy
ejb_guy

Reputation: 1125

 SELECT SUM(week1) + SUM(week2) + SUM(week3) + SUM(week4) + SUM(week5) +  
        SUM(week6) + SUM(week7) + SUM(week8) + SUM(week9) + SUM(week10) +  
        SUM(week11) + SUM(week12) + SUM(week13) 
 FROM results 
 WHERE username = '$username' 
 group by username

This should do the trick. (Assumption: There are multiple rows for each user. If each user has only one row than sum function and group by clause can be omitted)

Upvotes: 0

GordonM
GordonM

Reputation: 31740

SUM() is an aggregate function, for adding rows. To add columns simply use +, though be aware that if any of the columns is NULL you might not get the result you expected.

SELECT IFNULL(week1, 0) + IFNULL(week2, 0) + IFNULL(week3, 0) AS sumweeks //etc

Upvotes: 2

Taha Paksu
Taha Paksu

Reputation: 15616

SELECT week1 + week2 + week3 + week4 + week5 + week6 + week7 + week8 + week9 + 
week10 + week11 + week12 + week13 as sumweeks 
FROM results WHERE username = '$username'

would be enough

Upvotes: 0

Related Questions