Search code examples
phpmysqlpivotaggregate-functions

Change table to show records on the same line where the street address matches


I have a table that looks like the following:

enter image description here

But I want it to look like this so its easier for the user to read:

enter image description here

How do I change it to look like that? Here's the current code:

<?php

$sql = "SELECT
companyname,
ordernumber,
equipment,
theserial,
type,
theaddress
FROM table";

$result = mysqli_query($con, $sql);

?>


<table id="moreinfotable" name="moreinfotable" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>OrderNumber</th>
<th>Equipment</th>
<th>Serial</th>
<th>Type</th>
<th>Address</th>

</tr>
</thead>

<?php

while($row = mysqli_fetch_array($result)) { 

$companyname = $row['companyname'];
$ordernumber = $row['ordernumber'];
$equipment = $row['equipment'];
$theserial = $row['theserial'];
$type = $row['type'];
$theaddress = $row['theaddress'];

echo '<tr>';
echo '<td>' . $companyname . '</td>';
echo '<td>' . $ordernumber . '</td>';
echo '<td>' . $equipment . '</td>';
echo '<td>' . $theserial . '</td>';
echo '<td>' . $type . '</td>';
echo '<td>' . $theaddress . '</td>';
echo'</tr>';

} 

?>


</table>

Solution

  • For a fixed list of types (here, new delivery and pickup), you can pivot your dataset directly in SQL with conditional aggregation:

    select companyname, address,
        max(case when type = 'New Delivery' then ordernumber end) as delivery_ordernumber,
        max(case when type = 'New Delivery' then equipment   end) as delivery_equipment,
        max(case when type = 'New Delivery' then serial      end) as delivery_serial,
        max(case when type = 'Pickup'       then equipment   end) as pickup_equipment,
        max(case when type = 'Pickup'       then serial      end) as pickup_serial
    from mytable
    group by companyname, address