How to add a summed and grouped mysql query to a table

0

What I need is that in a table I show the sum of a field that is grouped:

$sql = "SELECT SUM(cantidad) AS cnt FROM produccion group by producto  ";



          <!-- Tabla donde se listará la consulta -->
          <table class="table table-striped">
            <thead>
              <tr>
                <th width="100">ID</th>
                <th width="250">Producto</th>             
                <th width="200">CNT</th>
                <th width="200">SUMA</th>
              </tr>
            </thead>
            <tbody>
            <!-- Generamos el listado vaciando las variables de la consulta en la tabla -->
              <?php

              while($persona = $consulta->fetch_assoc()) //Creamos un array asociativo con fetch_assoc

              {

              ?>
                <tr>
                  <td><?php echo $persona['id']; ?></td>
                  <td><?php echo $persona['producto']; ?></td>           
                  <td><?php echo $persona['cantidad']; ?></td>
                    <td><?php echo $persona['SUMA']; ?></td>
                  <td style="width:150px;">

                    </td>
                </tr>

              <?php
              }
              ?>
    
asked by juan perez 08.11.2018 в 21:31
source

1 answer

2

In your query you are doing the function SUM(cantidad) and you put an alias AS cnt then to get the result of the sum you have to print the alias

$sql = "SELECT SUM(cantidad) AS cnt FROM produccion group by producto";

    <!-- Tabla donde se listará la consulta -->
              <table class="table table-striped">
                <thead>
                  <tr>
                    <th width="100">ID</th>
                    <th width="250">Producto</th>             
                    <th width="200">CNT</th>
                    <th width="200">SUMA</th>
                  </tr>
                </thead>
                <tbody>
                <!-- Generamos el listado vaciando las variables de la consulta en la tabla -->
                  <?php

                  while($persona = $sql->fetch_assoc()) //Creamos un array asociativo con fetch_assoc

                  {

                  ?>
                    <tr>
                      <td><?php echo $persona['id']; ?></td>
                      <td><?php echo $persona['producto']; ?></td>           
                      <td><?php echo $persona['cnt']; ?></td>
                        <td><?php echo $persona['SUMA']; ?></td>
                      <td style="width:150px;">

                        </td>
                    </tr>

                  <?php
                  }
                  ?>
    
answered by 08.11.2018 / 22:03
source