How to retrieve the first record of each group after grouping in Oracle?

In Oracle, you can use grouping functions and subqueries to retrieve the first record from each group.

Suppose there is a table called “table_name” with two columns, “column1” and “column2”. We need to group by “column1” and retrieve the first record from each group.

You can use the following query statement:

SELECT column1, column2
FROM (
    SELECT column1, column2, ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2) AS rn
    FROM table_name
) t
WHERE rn = 1;

This query statement uses the window function ROW_NUMBER() to assign a sequential number (rn) to each record within a group, and sorts by “column2”. Then, in the outer query, it selects records where rn is equal to 1, meaning the first data entry within each group.

Please note that this method is applicable for Oracle 12c and above versions. If you are using an earlier version, you may need to utilize a different method to achieve this.

广告
Closing in 10 seconds
bannerAds