Dave Dave - 2 months ago 8
MySQL Question

Generate Sum of Occurrence of an action in PHP

I need assistance on how to generate the sum of occurrence of an exception from an entries that is capture daily on a weekly basis group by the offenders. take a look at my code which works for the offender but summing the offence totally instead of summing it for individual offender.

<tr>
<th>S/N</th>
<th>NAME</th>
<th>STAFF ID</th>
<th>ABS</th>
<th>BRK</th>
<th>BV</th>
<th>DUI</th>
<th>OS</th>
<th>OTH</th>
<th>Details of Other Offences</th>
</tr>
<?php
$get = mysqli_query($connection,"SELECT * FROM tab_incidence WHERE mainloc='$loc' AND cast(created_at as date) BETWEEN '$td1' AND '$td2' AND weekno='$wk' AND team='$tm' GROUP BY op ORDER BY fltno");
$c=0;$sumAbs=0;$sBrk=0;$sBv=0;$sDui=0;$sOs=0;$sOth=0;
while($rw = mysqli_fetch_array($get)){
$c++;
echo "<tr>";
echo "<td nowrap='nowrap'>". $c."</td>";
echo "<td nowrap='nowrap'>".$rw['op']."</td>";
echo "<td nowrap='nowrap'>".$rw['staffno']."</td>";
echo "<td nowrap='nowrap'>" .($rw['details']=='ABS'?$sumAbs=$sumAbs+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='BRK'?$sBrk=$sBrk+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='BV'?$sBv=$sBv+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='DUI'?$sDui=$sDui+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='OS'?$sOs=$sOs+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='OTH'?$sOth=$sOth+1:'0')."</td>";
echo "<td nowrap='nowrap'>". $rw['svalcom']."</td>";
echo "</tr>";
};}?>


I wantit to be able to sum each offence for each staff based on the weekno which is stored as week1, week2, week3. Note in each week, i have a record for each day that the offence is committed which will fall into week1 or 2 or 3 or 4.Any clue or assistance will be appreciated.

Answer

Step one: Find the staff who made any incident within a certain date (the week you are looking for)

SELECT distinct(staffno) as staff FROM tab_incidence WHERE mainloc='$loc' AND cast(created_at as date) BETWEEN '$td1' AND '$td2' AND weekno='$wk' AND team='$tm' 

Step 2: Loop the result

 while($rw = mysqli_fetch_array($get)){ // Pass by every staff

 // Query  for ABS is 
  SELECT count(id) as number FROM tab_incidence WHERE mainloc='$loc' AND cast(created_at as date) BETWEEN '$td1' AND '$td2' AND weekno='$wk' AND staffno='$rw["staff"]' AND details = 'ABS' // This will return the number of ABS offense per staff

}

Each type would require a query.

Comments