How to sum the amount column and also get data from your employee_salary table? It’s very easy and simple. When we learn about this topic, you can get your solution. In this article, we show how we did this solution.

Getting all salary results:

"SELECT SUM(amount) AS total_amount FROM employee_salary");

Getting 1000 salary results:

$result = mysqli_query($conn, "SELECT * FROM employee_salary ORDER BY id DESC LIMIT 1000");

Get the SUM from all salary results:


$sumResult = mysqli_query($conn, "SELECT SUM(amount) AS total_amount FROM employee_salary");
$sumRow = mysqli_fetch_assoc($sumResult);
$total_amount = $sumRow['total_amount'];
echo "Total Amount: " . $total_amount;

Getting 1000 results with SUM amount as total_amount:

$query = "    SELECT * ,  (SELECT SUM(amount) FROM employee_salary) AS total_amount     FROM employee_salary   ORDER BY id DESC   LIMIT 1000";
$result = mysqli_query($conn, $query);

Print the results that we are getting from the MySQL database

while ($row = mysqli_fetch_assoc($result)) {
    echo "ID: " . $row['id'] . " - Amount: " . $row['amount'] . "<br>";
    $total_amount = $row['total_amount'];  // It will be the same in every row
}
echo "Total Amount: " . $total_amount;

Explanation:

  • (SELECT SUM(amount) FROM employee_salary) AS total_amount calculates the total sum of the amount.
  • The main query retrieves the last 1000 records.
  • Every row in the result will contain a column total_amount with the same total sum value.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply