Home > Database > Mysql Tutorial > How to Retrieve the Top n Max Values from a Database Table?

How to Retrieve the Top n Max Values from a Database Table?

Barbara Streisand
Release: 2024-11-10 10:59:02
Original
693 people have browsed it

How to Retrieve the Top n Max Values from a Database Table?

Selecting Top Max Values from a Table

In database management, it can be necessary to retrieve the top n highest values from a table. To achieve this, there are several approaches available. Consider the following table:

column1  column2
   1       foo
   2       foo
   3       foo
   4       foo
   5       bar
   6       bar
   7       bar
   8       bar
Copy after login

For n=2, we want to obtain these results:

3    
4    
7    
8    
Copy after login

Approximation Using Group Max

An initial approach is to calculate the maximum value for each group:

SELECT max(column1) FROM table GROUP BY column2
Copy after login

However, this method only provides the top value for each group, not the top n values.

Union-Based Solution

For n=2, the following union-based query can be used:

SELECT max(column1) m
FROM table t
GROUP BY column2
UNION
SELECT max(column1) m
FROM table t
WHERE column1 NOT IN (SELECT max(column1)
                      WHERE column2 = t.column2)
Copy after login

This query selects the top values and then excludes duplicates by joining the second query, which finds the next highest value not already selected.

Rank Simulation

For any value of n, a more generic approach is to simulate the rank() function over partitions. One way to do this is:

SELECT t.*
FROM
   (SELECT grouper,
          (SELECT val
           FROM table li
           WHERE li.grouper = dlo.grouper
           ORDER BY
                 li.grouper, li.val DESC
           LIMIT 2,1) AS mid
   FROM
      (
      SELECT DISTINCT grouper
      FROM table
      ) dlo
   ) lo, table t
WHERE t.grouper = lo.grouper
      AND t.val > lo.mid
Copy after login

This query groups the values by the desired column and then finds the next highest value for each group within the specified limit (in this case, 2,1 for n=2).

By following these approaches, you can effectively select the top n max values from a given table, ensuring that duplicate values are eliminated and the correct number of records is returned.

The above is the detailed content of How to Retrieve the Top n Max Values from a Database Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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