简体   繁体   中英

Make sum for one column based on condition from another column in php?

I have one MySQL table with two columns: amount (INT) and address (string) . All addresses start with "A" or "B". How can I calculate the sum of all amounts for which address starts with "A" and sum of all amounts for which address start with "B"?

I would prefer to do this in PHP rather than in MySQL directly.

If the PHP request is not mandatory, you could simply do it with SQL .

You could use left and group by :

select left(address, 1) addr_part, sum(amount)
from my_table
group by addr_part

Doing it directly in MySQL , see scaisEdge's answer , is the way to go in my opinion, but since you want a PHP solution, you can try the following:

<?php
   # Create an array to store the results.
   $data = ["A" => 0, "B" => 0];

   # Initiate a db connection.
   $connection = new mysqli("localhost", "username", "password", "db");

   # Fetch the addresses and amounts from the database.
   $result = $connection -> query("SELECT `address`, `amount` FROM `table_name`");

   # Iterate over each row.
   while ($row = $result -> fetch_assoc()) {
      # Increment the value by the amount of the row.
      $data[$row["address"][0]] += $row["amount"];
   }
?>

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