MySQL sum() with group by – w3resource

MySQL SUM() function with group by

Last update on August 19 2022 21:50:42 (UTC/GMT +8 hours)

SUM() function with group by

MySQL SUM() function retrieves the sum value of an expression which has undergone a grouping operation by GROUP BY clause.

Example:

Sample table: purchase

Code:

SELECT cate_id,SUM(total_cost)
FROM purchase            
GROUP BY cate_id;

Relational Algebra Expression:

Relational Algebra Expression: MySQL SUM() function with group by.

Relational Algebra Tree:

Relational Algebra Tree: MySQL SUM() function with group by.

Explanation

The above MySQL statement returns the sum of ‘total_cost’ from purchase table for each group of category (‘cate_id’) .

Sample Output:

mysql> SELECT cate_id,SUM(total_cost)
    -> FROM purchase            
    -> GROUP BY cate_id;
+---------+-----------------+
| cate_id | SUM(total_cost) |
+---------+-----------------+
| CA001   |         1725.00 | 
| CA002   |          965.00 | 
| CA003   |          900.00 | 
+---------+-----------------+
3 rows in set (0.00 sec)

PHP script

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>example-aggregate-functions-and-grouping-sum-with-group-by- php mysql examples | w3resource</title>
<meta name="description" content="example-aggregate-functions-and-grouping-sum-with-group-by- php mysql examples | w3resource">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Category id and sum of total costs of purchases grouped by category id:</h2>
<table class='table table-bordered'>
<tr>
<th>Category id</th><th>Sum of total costs of purchases</th>
</tr>
<?php
$hostname="your_hostname";
$username="your_username";
$password="your_password";
$db = "your_dbname";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT cate_id,SUM(total_cost) 
FROM purchase
GROUP BY cate_id') as $row) {
echo "<tr>"; 
echo "<td>" . $row['cate_id'] . "</td>";
echo "<td>" . $row['SUM(total_cost)'] . "</td>";
echo "</tr>"; 
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

View the example in browser

JSP script

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example-aggregate-functions-and-grouping-sum-with-group-by</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String Host = "jdbc:mysql://localhost:3306/w3resour_bookinfo";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
connection = DriverManager.getConnection(Host, "root", "datasoft123");
statement = connection.createStatement();
String Data = "SELECT cate_id,SUM(total_cost) FROM purchase GROUP BY cate_id";
rs = statement.executeQuery(Data);
%>
<TABLE border="1">
<tr width="10" bgcolor="#9979">
<td>Category id</td>
<td>Sum of total costs of purchases</td>
</tr>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString("cate_id")%></TD>
<TD><%=rs.getString("SUM(total_cost)")%></TD>
</TR>
<%   }    %>
</table>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
out.println("Can’t connect to database.");
}
%>
</body>
</html>

Online Practice Editor:

Previous:
SUM()
Next:
VAR_POP()



Alternate Text Gọi ngay