Home >Database >Mysql Tutorial >How to Find the Maximum Value for Each Group in a Database Table?
Use relational function to find the maximum value of each grouping
In databases, it is common to group and aggregate data to extract meaningful insights. One such aggregate function is to select the maximum value for each data group.
Let's consider a hypothetical table called "out_pumptable" that contains pump usage information organized by pump name ("name"), value ("value"), and another column ("AnotherColumn"). Sample data looks like this:
<code>Name Value AnotherColumn ----------- Pump 1 8000.0 Something1 Pump 1 10000.0 Something2 Pump 1 10000.0 Something3 Pump 2 3043 Something4 Pump 2 4594 Something5 Pump 2 6165 Something6</code>
Grouping and maximum aggregation
To select the maximum value for each pump, we use GROUP BY and MAX() functions in SQL. The following query can accomplish this task:
<code>SELECT name, MAX(value) FROM out_pumptable GROUP BY name</code>
Query Understanding
Solve duplicate entry problem
In the given example code, there may be duplicate entries for pumps with the same maximum value. This is because the query matches each row with the maximum value, resulting in redundant entries.
To solve this problem, we can modify the query to select different combinations of "name" and "value":
<code>SELECT DISTINCT name, MAX(value) FROM out_pumptable GROUP BY name</code>
This modification ensures that each pump only appears once, even if it has multiple rows with the same maximum value.
The above is the detailed content of How to Find the Maximum Value for Each Group in a Database Table?. For more information, please follow other related articles on the PHP Chinese website!