Функция MySQL SUM () с группировкой по
Функция SUM () с группировкой по
Функция MySQL SUM () извлекает значение суммы выражения, которое подверглось операции группировки по предложению GROUP BY.
Пример:
Пример таблицы: покупка
Код:
SELECT cate_id,SUM(total_cost)
FROM purchase
GROUP BY cate_id;
объяснение
Вышеуказанный оператор MySQL возвращает сумму «total_cost» из таблицы покупок для каждой группы категории («cate_id»).
Пример вывода:
mysql> SELECT cate_id, SUM (total_cost) -> ОТ покупки -> GROUP BY cate_id; + --------- + ----------------- + | cate_id | SUM (total_cost) | + --------- + ----------------- + | CA001 | 1725,00 | | CA002 | 965,00 | | CA003 | 900,00 | + --------- + ----------------- + 3 ряда в наборе (0,00 сек)
PHP скрипт
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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>
JSP скрипт
<%@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>
Предыдущая: СУММА ()
Далее: VAR_POP ()
Новый контент: Composer: менеджер зависимостей для PHP , R программирования
disqus2code