将SQL字段汇总在一起获得总结果

时间:2012-05-29 05:49:00

标签: php sql

我试图在SQL数据库中求和一些字段。 这些字段称为第1周到第13周,因为它们存储每周的结果。 我现在有这个,但它没有输出任何东西,任何帮助将不胜感激。干杯

<?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;

            }
        ?>

3 个答案:

答案 0 :(得分:2)

SUM()是一个聚合函数,用于添加行。要添加列,只需使用+,但请注意,如果任何列为NULL,您可能无法获得预期的结果。

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

答案 1 :(得分:0)

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

就足够了

答案 2 :(得分:0)

 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

这应该可以解决问题。 (假设:每个用户有多行。如果每个用户只有一行而不是sum函数,则group by子句可以省略)