The Rows Holding the Group-wise Maximum of a Certain Column in MySQL

MySQLMySQLi Database

Let us understand how to find the rows that hold the group wise maximum of a specific column in MySQL −

The syntax to find the rows that hold the group-wise maximum of a specific column in MySQL is as follows −

SELECT colName1, colName2, colName3
FROM tableName s1
WHERE colName3=(SELECT MAX(s2. colName3)
FROM tableName s2
WHERE s1. colName1= s2. colName1)
ORDER BY colName1;

Let’s say we have the following PRODUCT Table −

<PRODUCT>

+---------+----------+--------+
| Article | Warehouse| Price  |
+---------+----------+--------+
| 1       | North    | 255.50 |
| 1       | North    | 256.05 |
| 2       | South    | 90.50  |
| 3       | East     | 120.50 |
| 3       | East     | 123.10 |
| 3       | East     | 122.10 |
+---------+----------+--------|

Following is the query −

Query

SELECT Article, Warehouse, Price
FROM Product p1
WHERE Price=(SELECT MAX(p2. Price)
FROM Product p2
WHERE p1. Article= p2. Article)
ORDER BY Article;

Output

+-------------+----------------+------------+
| Article     | Warehouse      | Price      |
+-------------+----------------+------------+
| 0001        | North          | 256.05     |
| 0002        | South          | 90.50      |
| 0003        | East           | 123.10     |
+-------------+----------------+------------+

The above query used a correlated subquery.

raja
Published on 09-Mar-2021 13:07:40
Advertisements