开发者

Sum of a count field to get overall total

开发者 https://www.devze.com 2023-03-11 13:02 出处:网络
I am very new to this and am looking for some help. I am replicating a report in my current system with the following code.

I am very new to this and am looking for some help. I am replicating a report in my current system with the following code.

    <?php
     foreach ($possibleSanctionsAssociativeArray as $currentSanction => $currentSanctionDetailsArray)
    {   
        $tableHeadersArray = array ('Home Office',' Total');

        $query = "SELECT home_office, COUNT(file_id) FROM cases WHERE ".$currentSanction."='Yes' and ($refdate>='$begindate' AND $refdate<='$enddate') GROUP BY home_office";

        $title = "<p class='report_title'> <b>".getSanctionDescr开发者_如何学PythoniptiveName($currentSanction)."</b>";
        simpleStatTable($query, $tableHeadersArray, $title);
    }
    ?>

It displays a Table with two columns and two rows:

HOME OFFICE    |    Total

OJA            |     82

ORL            |    634

I would like it to display a third row that says "OVERALL TOTAL | 716"

I have tried several solutions with no luck, I think I am struggling with the sum of a count field, then displaying the count.

Thanks for all the help in advance.


As it was said, never use a query inside a loop unless it's really needed. About getting the whole sum, in case you're using MySQL, you could use the WITH ROLLUP.


I'm unsure about the performance implications of this one, but you could try

SELECT SUM(totals) FROM (SELECT home_office, COUNT(file_id) AS totals FROM cases WHERE ".$currentSanction."='Yes' and ($refdate>='$begindate' AND $refdate<='$enddate') GROUP BY home_office AS counts_table)


I misunderstood the question at first. This should work:

$query = "SELECT home_office, COUNT(file_id) FROM cases
            WHERE ".$currentSanction."='Yes' and ($refdate>='$begindate' AND $refdate<='$enddate')
            GROUP BY home_office
          UNION
          SELECT 'Overall Total' AS home_office, COUNT(file_id) FROM cases
            WHERE ".$currentSanction."='Yes' and ($refdate>='$begindate' AND $refdate<='$enddate');";


$countTotal = 0;
foreach() {
   $query = /*...*/
   $row = mysql_fetch_*($query);
   $countTotal += $row['count'];   
}

echo $countTotal;

Anyway never put a query inside a loop, use Join instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消