w3resource logo


>Rows holding group wise maximum for a column

MySQL : Rows holding group wise maximum

rating has average rating 7 out of 10. Total 6 users rated.

<<PreviousNext>>

Description

In this page we have shown how to retrieve the rows holding group wise maximum for a column.

In the example shown and explained in this page, we retrieved the most expensive books of each language.

Example :

Sample table : book_mast

Code

SELECT book_name, pub_lang, book_price
FROM book_mast b1
WHERE book_price = 
SELECT MAX( b2.book_price )
FROM book_mast b2
WHERE b1.pub_lang = b2.pub_lang ); 

Explanation

The above MySQL statement has performed the following -

1. book_name, pub_lang, book_price are retrieved from book_mast, if

a) language of the most costly book of book_mast aliased as b2 and b1 are alike.

Output

mysql rows holding group wise maximum for a column

PHP script

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>example-php-mysql-bit_count()</title>
</head>
<body>
<?php
echo "<h2>List of most expensive books of each language : </h2>";
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='250' align='center'>Book</td><td width='250' align='center'>Language</td><td width='250' align='center'>Price</td>";
echo "</tr>";
include("../dbopen.php");
$result = mysql_query("SELECT book_name, pub_lang, book_price
FROM book_mast b1
WHERE book_price = (
SELECT MAX( b2.book_price )
FROM book_mast b2
WHERE b1.pub_lang = b2.pub_lang )");
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td align='center' width='200'>" . $row['book_name'] . "</td>";
echo "<td align='center' width='200'>" . $row['pub_lang'] . "</td>";
echo "<td align='center' width='200'>" . $row['book_price'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

View the example in browser

photo credit: 1967geezer Photo is used under creative Common License.

<<PreviousNext>>