In actual database queries, we often encounter the need to obtain duplicate data from Get the only piece of data. This article will introduce how to use Oracle database techniques to obtain only one record in duplicate data, and provide specific code examples.
Suppose we have a table named employee
, which contains employee information. There may be duplicate employee information. We need to query any record of all duplicate employee information, rather than obtain all duplicate employee information.
We can use the window function ROW_NUMBER()
in Oracle database combined with the PARTITION BY
statement to achieve this requirement. The specific implementation idea is to assign a serial number to each record, and then filter out the record with the serial number 1 to obtain the first record in each set of repeated data.
The following is a specific code example based on the above idea:
SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (PARTITION BY e.employee_id ORDER BY e.employee_id) AS rn FROM employee e ) tmp WHERE rn = 1;
In the above code, a serial number rn
is first added to each record through a subquery, and Group based on employee_id
field. Then filter out the record with serial number 1 in the external query, and you can get the first record in each set of repeated data.
Assume that the employee
table has the following structure:
employee_id | name | department |
---|---|---|
1 | 张三 | Technical Department |
2 | 李四 | Sales Department |
3 | 王五 | Finance Department |
1 | 张三 | Technical Department |
2 | 李思 | Sales Department |
After executing the above code example, the following results will be returned:
employee_id | name | department |
---|---|---|
张三 | Technical Department | |
李四 | Sales Department | |
王五 | Finance Department |
ROW_NUMBER() and the
PARTITION BY statement, we can easily achieve this requirement, improving query efficiency and data processing accuracy. I hope this article will be helpful to you in your actual database query work.
The above is the detailed content of Oracle database query skills: get only one piece of duplicate data. For more information, please follow other related articles on the PHP Chinese website!