简体   繁体   English

根据php中另一列的条件为一列求和?

[英]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) .我有一个包含两列的MySQL表: amount (INT)address (string) All addresses start with "A" or "B".所有地址都以“A”或“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"?如何计算地址以“A”开头的所有金额的总和以及地址以“B”开头的所有金额的总和?

I would prefer to do this in PHP rather than in MySQL directly.我更愿意在PHP而不是直接在MySQL执行此操作。

If the PHP request is not mandatory, you could simply do it with SQL .如果PHP请求不是强制性的,您可以简单地使用SQL

You could use left and group by :您可以使用leftgroup 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:直接在MySQL ,请参阅scaisEdge 的答案,在我看来是可行的方法,但是由于您想要一个PHP解决方案,您可以尝试以下操作:

<?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"];
   }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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