Hola, el origen de la consulta es que tengo una tabla llamada
contabilidad, con la siguiente estructura
Código PHP:
CREATE TABLE `contabilidad` (
`n_id` int(11) NOT NULL,
`n_id_comunidades` tinyint(4) NOT NULL,
`n_id_grupos` int(11) NOT NULL,
`f_fecha` date NOT NULL,
`c_concepto` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
`n_importe` decimal(12,2) NOT NULL,
`n_saldo` decimal(12,2) NOT NULL,
`f_registro` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Esta tabla es un diario contable con registros de varios años, y lo que pretendía hacer con una consulta SQL era obtener el resumen de los gastos agrupado por meses del año actual y anterior, para mostrarlo en una tabla.
Al final lo conseguido pasando los resultados de las 4 consultas (GASTOS mensuales año actual, GASTOS mensuales año anterior, INGRESOS mensuales año actual, INGRESOS mensuales año anterior), a un Array() y después los he puesto en una tabla, el resultado es el de esta imagen.
El codigo PHP PDO que he utilizado es el siguiente:
Código PHP:
<?php
$hoy = getdate(); //array datos sistema para obtener el año.;
require_once('conexion.php');
$db=Db::conectar();
// gastos año anterior
$select=$db->prepare('
select Month(f_fecha) as Month, sum(n_importe) as n_importe from contabilidad WHERE YEAR(f_fecha) =:yearAnterior and n_importe<0 Group By Month');
$select->bindValue('yearAnterior',$hoy['year']-1);
$select->execute();
$año_anterior = $select->fetchAll(PDO::FETCH_ASSOC);
// gastos año actual
$select=$db->prepare('
select count(*), Month(f_fecha) as Month, sum(n_importe) as n_importe from contabilidad where YEAR(f_fecha) =:yearActual and n_importe<0 Group By Month');
$select->bindValue('yearActual',$hoy['year']);
$select->execute();
$año_actual = $select->fetchAll(PDO::FETCH_ASSOC);
$filas=$select->rowCount(); // obtenemos el nº de filas recibidas
// rellenamos con cero el array de los meses que no hay datos
for($i=$filas;$i<12;$i++) {
$año_actual[$i]['Month']=$i;
$año_actual[$i]['n_importe']=0.00;
}
// ingresos año anterior
$select=$db->prepare('
select Month(f_fecha) as Month, sum(n_importe) as n_importe from contabilidad WHERE YEAR(f_fecha) =:yearAnterior and n_importe>=0 Group By Month');
$select->bindValue('yearAnterior',$hoy['year']-1);
$select->execute();
$i_año_anterior = $select->fetchAll(PDO::FETCH_ASSOC);
// ingresos año actual
$select=$db->prepare('
select count(*), Month(f_fecha) as Month, sum(n_importe) as n_importe from contabilidad where YEAR(f_fecha) =:yearActual and n_importe>=0 Group By Month');
$select->bindValue('yearActual',$hoy['year']);
$select->execute();
$i_año_actual = $select->fetchAll(PDO::FETCH_ASSOC);
$filas=$select->rowCount(); // obtenemos el nº de filas recibidas
// rellenamos con cero el array de los meses que no hay datos
for($i=$filas;$i<12;$i++) {
$i_año_actual[$i]['Month']=$i;
$i_año_actual[$i]['n_importe']=0.00;
}
echo "<div style='overflow-x:auto'>";
echo "<table border='1' id='mitabla' >";
echo "<thead>";
echo "<tr>";
echo "<th class='table-header' width='10%'> </th>";
echo "<th class='table-header' width='22%'>Gastos</th>";
echo "<th class='table-header' width='22%'>Gastos</th>";
echo "<th class='table-header' width='22%'>Ingresos</th>";
echo "<th class='table-header' width='22%'>Ingresos</th>";
echo "</tr>";
echo "</thead>";
echo "<thead>";
echo "<tr>";
echo "<th>Mes</th>";
echo "<th><div class='links'>
<a class='active' href='cta_bancaria.php'>".$hoy['year']."</a></th> </div>";
echo "<th><div class='links'>
<a class='active' href='cta_bancaria.php'>".($hoy['year']-1)."</a></th> </div>";
echo "<th>".$hoy['year']."</th>";
echo "<th>".($hoy['year']-1)."</th>";
echo "</tr>";
echo "</thead>";
$total_actual=0;
$total_anterior=0;
$i_total_actual=0;
$i_total_anterior=0;
$meses = array("-","Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
for($i=0;$i<12;$i++) { // recorremos el array. NOTA: debe haber datos en todos los items
echo "<tbody>";
echo "<tr>";
echo " <td> ".$meses[$año_anterior[$i]['Month']]."</td>";
echo " <td ALIGN='right'> ".number_format($año_actual[$i]['n_importe'], 2, ',', '.')."</td>";
echo " <td ALIGN='right'> ".number_format($año_anterior[$i]['n_importe'], 2, ',', '.')."</td>";
echo " <td ALIGN='right'> ".number_format($i_año_actual[$i]['n_importe'], 2, ',', '.')."</td>";
echo " <td ALIGN='right'> ".number_format($i_año_anterior[$i]['n_importe'], 2, ',', '.')."</td>";
echo "</tr>";
$total_actual = $total_actual + $año_actual[$i]['n_importe'];
$total_anterior = $total_anterior + $año_anterior[$i]['n_importe'];
$i_total_actual = $i_total_actual + $i_año_actual[$i]['n_importe'];
$i_total_anterior= $i_total_anterior + $i_año_anterior[$i]['n_importe'];
}
echo "<tr>";
echo " <td> TOTAL </td>";
echo " <td ALIGN='right'> ".number_format($total_actual, 2, ',', '.')."</td>";
echo " <td ALIGN='right'> ".number_format($total_anterior, 2, ',', '.')."</td>";
echo " <td ALIGN='right'> ".number_format($i_total_actual, 2, ',', '.')."</td>";
echo " <td ALIGN='right'> ".number_format($i_total_anterior, 2, ',', '.')."</td>";
echo "</tr>";
echo "</tbody>";
echo "</tr>";
echo "</table>";
echo "</div>";
?>
No se si hay otra forma de realizarlo más eficaz, pero esta funciona bastante bien.
Un saludo y muchas gracias a todos.