Home > Database > Mysql Tutorial > How to Retrieve Distinct Rows with the Minimum Value in SQL?

How to Retrieve Distinct Rows with the Minimum Value in SQL?

Linda Hamilton
Release: 2025-01-24 08:17:08
Original
249 people have browsed it

How to Retrieve Distinct Rows with the Minimum Value in SQL?

Extracting Unique Rows with Minimum Values Using SQL

SQL queries frequently involve selecting specific rows based on defined conditions. A common scenario is retrieving the row with the minimum value in a column, while ensuring that only unique rows are returned.

Let's illustrate with this sample table:

<code>id | game | point
-------+--------+--------
1  | x    | 5
1  | z    | 4
2  | y    | 6
3  | x    | 2
3  | y    | 5
3  | z    | 8</code>
Copy after login

To obtain the id with the lowest point value for each game, we can employ a subquery and an inner join. The subquery identifies the minimum point for each id:

SELECT Id, MIN(Point) AS MinPoint
FROM TableName
GROUP BY Id
Copy after login

This subquery yields ids and their respective minimum point values. The main query then joins this result with the original table, filtering for rows matching the minimum points:

SELECT tbl.*
FROM TableName tbl
INNER JOIN (
    SELECT Id, MIN(Point) AS MinPoint
    FROM TableName
    GROUP BY Id
) tbl1 ON tbl1.id = tbl.id
WHERE tbl1.MinPoint = tbl.Point;
Copy after login

The query's output:

<code>id | game | point
-------+--------+--------
1  | z    | 4
3  | x    | 2
2  | y    | 6</code>
Copy after login

This method effectively returns unique rows containing the minimum point value for each id, providing a clean dataset for subsequent analysis.

The above is the detailed content of How to Retrieve Distinct Rows with the Minimum Value in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template