Como sumar columnas de una tabla

Tengo mi siguiente código

¿

¿
<?php
    include("../assets/includes/conexion.php");
    include('../fechas_de_corte.php');
$sqlrx = "SELECT *,
        COUNT(nombre) AS totalpacientes,
        SUM(tx) AS tx,
        SUM(ab) AS ab, 
        SUM(sup) AS sup,
        SUM(inf) AS inf,
        SUM(col) AS col,
        SUM(cra) AS cra,
        SUM(senpar) AS senpar,
        SUM(pel) AS pel
        FROM estudios_rx WHERE fecha BETWEEN '$fechacortede' AND '$fechacortehasta'
        GROUP BY tecnico
        ";
$rrx=mysqli_query($conexion, $sqlrx);
?>
<html>
<h1 align="center">¿Estudios del mes de?</h1>
    <table width="70%" border="1px" align="center">
    <tr align="center">
        <td>tecnico</td>
        <td>Estudios</td>
        <td>Pacientes</td>
    </tr>
    <?php 
        while($rowrx = mysqli_fetch_array($rrx))
        {
        $totalestudios = $rowrx['tx'] + $rowrx['ab'] + $rowrx['sup'] + $rowrx['inf'] + $rowrx['col']  + $rowrx['cra'] + $rowrx['senpar'] + $rowrx['pel'];
    ?>
    <tr>
        <td><?php echo $rowrx["tecnico"]?></td>
        <td><?php echo $totalestudios?></td>
        <td><?php echo $rowrx["totalpacientes"]?></td>
    </tr>
    <?php 
        }
    ?>
    </table>

Me imprime esta tabla

Ya intente e intente busque en google y no pudo hacer lo siguiente....

Que me sume los totales.

1 Respuesta

Respuesta
1

Víctor,

Esta es una opción:

$tbody = '';
$total_estudios = 0;
$total_pacientes = 0;
$qry = mysqli_query($conexion, "SELECT
    tecnico,
    (SUM(tx) + SUM(ab) + SUM(sup) + SUM(inf) + SUM(col) + SUM(cra) + SUM(senpar) + SUM(pel)) AS total_estudios,
    COUNT(nombre) AS total_pacientes
  FROM estudios_rx
  WHERE fecha BETWEEN '$fechacortede' AND '$fechacortehasta'
  GROUP BY tecnico
;");
while($row = mysqli_fetch_array($qry)){
  $tbody .= "
    <tr>
      <td>".$row['tecnico']."</td>
      <td>".$row['total_estudios']."</td>
      <td>".$row['total_pacientes']."</td>
    </tr>
  ";
  $total_estudios += $row['total_estudios'];
  $total_pacientes += $row['total_pacientes'];
}
?>
<table>
  <thead>
    <tr>
      <th>Técnico</th>
      <th>Estudios</th>
      <th>Pacientes</th>
    </tr>
  </thead>
  <tbody>
    <?php echo $tbody ?>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>$total_estudios</td>
      <td>$total_pacientes</td>
    </tr>
  </tfoot>
</table>

Como puedes ver, dejé inicializadas dos variables ($total_estudios y $total_pacientes) para que almacenen el total el cual se calcula en el while. Los valores finalmente los muestras en el pie del table.

Otra opción es hacerlo desde la base de datos realizando una consulta union que haga la suma de toda la columna.

http://70y7.com/  

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas