简体   繁体   中英

PHP Sum column values if multiple keys are the same MySql

I have following table which results are fetched from mysql query. These values are for example only.

Item | Location |  CheckIn   |  Checkout  | Quantity

  A  |   abc    | 10/10/2015 |            |    20
  A  |   abc    |            | 11/10/2015 |    10
  B  |   def    | 11/10/2015 |            |    25
  A  |   abc    | 12/10/2015 |            |    5
  B  |   def    |            | 13/10/2015 |    10
  B  |   def    | 14/10/2015 |            |    3
  A  |   ghi    | 14/10/2015 |            |    30

I want to total up the quantity based on same item and location, and with condition. For example, if item check in, quantity of the item is added up into the location. If item check out, quantity of the item is subtracted from total current quantity of item at specific location.

I have second table which will display each item at specific location with total quantity of the item at that location. What I have so far is something like this:

Item | Location | Total Quantity

  A  |   abc    |  20
  A  |   abc    |  10
  B  |   def    |  35
  A  |   abc    |  40
  B  |   def    |  30
  B  |   def    |  33
  A  |   ghi    |  63

The expected result should be like this:

Item | Location | Total Quantity

  A  |   abc    |  15
  B  |   def    |  18
  A  |   ghi    |  30

The code I did so far for second table:

<?php
$result = mysql_query("SELECT * FROM itemloc INNER JOIN tblitem ON itemloc.itemId=tblitem.itemId INNER JOIN tblloc ON itemloc.locId=tblloc.locId");
$loc = array();
$total = 0;

while($row = mysql_fetch_array($result))
{
$checkout = $row['itemLocCheckOut'];
if($loc[$row['locId']] = $row['itemId']){
    if(is_null($checkout)){
        $qty = +$row['itemLocQty'];
        }
    else{
        $qty = -$row['itemLocQty'];
        }
$total+=$qty;
$name = $row['itemNm'];
$locnm = $row['locNm'];
}
?>
<tr>
    <td><?php echo $name;?></td>
    <td><?php echo $locnm;?></td>
    <td><?php echo $total;?></td>
</tr>

<?php
}
?>

Any help would be much appreciated. Thank you.

I would make an array with first index item string and the second the Location.
For each row read, I would do:

while($row = mysql_fetch_array($result))
{
    $item = $row['item'];
    $location = $row['location'];
    if(!isset($result[$item][$location]))
        $result[$item][$location] = 0;
    if(is_null($row['itemLocCheckOut']))
        $result[$item][$location] += $row['quantity'];
    else
        $result[$item][$location] -= $row['quantity'];
}

At the end, pass with 2 foreach on the table:

foreach($result as $k1 => $v1)
    foreach($v1 as $k2 => $v2)
         echo "Item $k1 location $k2 has $v2 quantity"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM