MySQL MAX() function with group by – w3resource

MySQL MAX() function with group by

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

MAX() function with group by

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).

Example

Sample table: book_mast

Code:

SELECT cate_id, MAX( book_price)
FROM book_mast
GROUP BY cate_id;

Relational Algebra Expression:

Relational Algebra Expression: MAX() function with group by.

Relational Algebra Tree:

Relational Algebra Tree: MAX() function with group by.

Explanation

The above MySQL statement will extract all “cate_id”s and the maximum ‘book_price’ in each group of ‘cate_id’. ‘GROUP BY ‘ clause have grouped “cate_id’s”.

Sample Output:

mysql> SELECT cate_id, MAX(book_price)
    -> FROM book_mast
    -> GROUP BY cate_id;
+---------+-----------------+
| cate_id | MAX(book_price) |
+---------+-----------------+
| CA001   |          145.00 | 
| CA002   |          250.00 | 
| CA003   |          200.00 | 
| CA004   |          100.00 | 
| CA005   |          180.00 | 
+---------+-----------------+
5 rows in set (0.02 sec)

Pictorial Presentation

mysql aggregate functions and grouping max function group by pictorial presentation

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-MAX-with-group-by- php MySQL examples | w3resource</title>
<meta name="description" content="example-MAX-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>Extracting all cate_id's and the maximum 'book_price'  in each group of 'cate_id'. ‘GROUP BY ‘ clause have grouped 'cate_id's:</h2>
<table class='table table-bordered'>
<tr>
<th>Category id</th><th>maximum book price</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, MAX(book_price)
FROM book_mast
GROUP BY cate_id') as $row) {
echo "<tr>";
echo "<td>" . $row['cate_id'] . "</td>";
echo "<td>" . $row['MAX(book_price)'] . "</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-max()</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, MAX(book_price) FROM book_mast GROUP BY cate_id";
rs = statement.executeQuery(Data);
%>
<TABLE border="1">
<tr width="10" bgcolor="#9979">
<td>category id</td>
<td>maximum book price</td>
</tr>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString("cate_id")%></TD>
<TD><%=rs.getString("MAX(book_price)")%></TD>
</TR>
<%   }    %>
</table>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
out.println("Can’t connect to database.");
}
%>
</body>
</html>

MySQL MAX() function with group by on two columns

Sample table: publisher

Code:

SELECT country,pub_city,MAX(no_of_branch)             
FROM publisher           
GROUP BY country,pub_city;

Relational Algebra Expression:

Relational Algebra Expression: MySQL MAX() function with group by on two columns.

Relational Algebra Tree:

Relational Algebra Tree: MySQL MAX() function with group by on two columns.

Explanation

The above MySQL statement will extract those countries (‘country’) and publisher cities (‘pub_city’) which has the maximum number of branches (‘no_of_branch’) in each group of ‘country’ and ‘pub_city’.

Sample Output:

mysql> SELECT country,pub_city,MAX(no_of_branch)
    -> FROM publisher
    -> GROUP BY country,pub_city;
+-----------+-----------+-------------------+
| country   | pub_city  | MAX(no_of_branch) |
+-----------+-----------+-------------------+
| Australia | Adelaide  |                 6 | 
| India     | Mumbai    |                10 | 
| India     | New Delhi |                10 | 
| UK        | Cambridge |                 6 | 
| UK        | London    |                 8 | 
| USA       | Houstan   |                25 | 
| USA       | New York  |                15 | 
+-----------+-----------+-------------------+
7 rows in set (0.02 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-MAX-with-group-by-on-two-columns- php MySQL examples | w3resource</title>
<meta name="description" content="example-MAX-with-group-by-on-two-columns- 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>List of country, city and maximum number of branches of publishers:</h2>
<table class='table table-bordered'>
<tr>
<th>Country</th><th>City</th><th>maximum no of branches</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 country,pub_city,MAX(no_of_branch)
FROM publisher
GROUP BY country,pub_city') as $row) {
echo "<tr>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['pub_city'] . "</td>";
echo "<td>" . $row['MAX(no_of_branch)'] . "</td>";
echo "</tr>";
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

View the example in browser

MySQL MAX with group by and order by

Code:

SELECT country,pub_city,MAX(no_of_branch)              
FROM publisher           
GROUP BY country,pub_city           
ORDER BY country;

Relational Algebra Expression:

Relational Algebra Expression: MySQL MAX with group by and order by.

Relational Algebra Tree:

Relational Algebra Tree: MySQL MAX with group by and order by.

Explanation

The above MySQL statement will extract those countries (‘country’) and publisher cities (‘pub_city’) which have the maximum number of branches (‘no_of_branch’) for each group of ‘country’ and ‘pub_city’. ‘GROUP BY ‘ clause have grouped ‘country’ and ‘pub_city’ . The ‘country’ column have sorted in ascending order by the usage of ORDER BY clause.

Sample Output:

mysql> SELECT country,pub_city,MAX(no_of_branch)
    -> FROM publisher
    -> GROUP BY country,pub_city
    -> ORDER BY country;
+-----------+-----------+-------------------+
| country   | pub_city  | MAX(no_of_branch) |
+-----------+-----------+-------------------+
| Australia | Adelaide  |                 6 | 
| India     | Mumbai    |                10 | 
| India     | New Delhi |                10 | 
| UK        | Cambridge |                 6 | 
| UK        | London    |                 8 | 
| USA       | Houstan   |                25 | 
| USA       | New York  |                15 | 
+-----------+-----------+-------------------+
7 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-MAX-with-group-by-and-order-by- php MySQL examples | w3resource</title>
<meta name="description" content="example-MAX-with-group-by-and-order-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>List of country, city and maximum number of branches of publishers, arranged in ascending order:</h2>
<table class='table table-bordered'>
<tr> 
<th>Country</th><th>City</th><th>maximum no of branches</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 country,pub_city,MAX(no_of_branch)
FROM publisher
GROUP BY country,pub_city
ORDER BY country') as $row) {
echo "<tr>"; 
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['pub_city'] . "</td>"; 
echo "<td>" . $row['MAX(no_of_branch)'] . "</td>";
echo "</tr>"; 
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

View the example in browser

MySQL MAX() function with distinct

MAX() function with distinct

MySQL MAX() function retrieves the maximum value of an expression if the function is accompanied by a DISTINCT clause.

Example:

Sample table: book_mast

Code:

SELECT cate_id,MAX(DISTINCT no_page)
FROM book_mast 
GROUP BY cate_id;

Relational Algebra Expression:

Relational Algebra Expression: MySQL  MAX() function with distinct.

Relational Algebra Tree:

Relational Algebra Tree: MySQL  MAX() function with distinct.

Explanation

The above MySQL statement will extract category (‘cat_id’) wise maximum number of pages (‘no_page’) from the ‘book_mast’ table.

Sample Output:

mysql> SELECT cate_id,MAX(DISTINCT no_page)
    -> FROM book_mast
    -> GROUP BY cate_id;
+---------+-----------------------+
| cate_id | MAX(DISTINCT no_page) |
+---------+-----------------------+
| CA001   |                   345 | 
| CA002   |                   600 | 
| CA003   |                   510 | 
| CA004   |                   350 | 
| CA005   |                   350 | 
+---------+-----------------------+
5 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-MAX-with-distinct- php MySQL examples | w3resource</title>
<meta name="description" content="example-MAX-with-distinct- 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>List of category id and maximum unique number of pages of books belong to those categories:</h2>
<table class='table table-bordered'>
<tr>  
<th>Category id</th><th>MAX(DISTINCT no_page)</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,MAX(DISTINCT no_page)
FROM book_mast
GROUP BY cate_id') as $row) {
echo "<tr>";
echo "<td>" . $row['cate_id'] . "</td>";
echo "<td>" . $row['MAX(DISTINCT no_page)'] . "</td>";
echo "</tr>";
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

View the example in browser



Alternate Text Gọi ngay