In my MySQL database I have something like this:
My class gets the records
public function listarMatriz() {
$sql = "SELECT codigo, tipo, importe FROM tabla WHERE CONDICION";
$bd = new Conn();
$stmt = $bd->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC)) {
return $row;
}
How do I create the matrix: CODIGO, TIPO_A, TIPO_B, TIPO_C
And that the values are displayed as follows:
An additional consideration is that the TYPE field has an indeterminate variable amount.
What you are looking to make is a Pivot table which you can achieve as follows
EXPLANATION
SUM
to make a sum of all the values but whenCASE
it detects each specific case for exampletipo
isa
then it will make a sum of the columnimporte
and at the end for each case (which in this case are 3) we will assign an aliasSUM
at the end, I must group the results by a column, which in this case iscodigo
Important note
Optionally if you want to group the results you can do the following in your query
What will give you as a result
Link to working example sql example