Add values from a select when repeat client id

Asked

Viewed 150 times

5

How I could sum the values of a select when repeating the account id?

Example

I use that select:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM clientes";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo  $row["nome"]. " - " . $row["valor"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();

Upshot:

Manoel - R$20,00

Manoel - R$40,00

Isac- R$60,00

Isac- R$40,00

João- R$40,00

How I need you to keep adding up the values without repeating customer names:

Manoel - R$60,00

Isac- R$100,00

João- R$40,00

  • Read about the group by of SQL.

2 answers

5


You need to use the group by of SQL.

For the result you want to query would be:

SELECT nome, SUM(valor) valor FROM clientes GROUP BY nome

2

Group the result by user name using the clause GROUP BY and use the function SUM to sum these grouped results.

Modify your query to look like this:

$sql = "SELECT nome, SUM(valor) FROM clientes GROUP BY nome";

In the link I’m leaving below has a very complete answer of how this clause works GROUP BY of SQL.

Link: DISTINCT and GROUP BY, what is the difference between the two statements?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.