Home > Database > Mysql Tutorial > How to Assign Row Numbers to Distinct Values in SQL?

How to Assign Row Numbers to Distinct Values in SQL?

Patricia Arquette
Release: 2024-12-29 20:52:16
Original
463 people have browsed it

How to Assign Row Numbers to Distinct Values in SQL?

Distinct Row Numbers in SQL using Row_Number

Distinct queries in SQL are used to retrieve unique values from a specified column. However, there are scenarios where it's desirable to not only display distinct values but also their corresponding row numbers. To achieve this, the Row_Number function can be utilized in conjunction with the DISTINCT keyword.

In the example provided, the user attempted to combine DISTINCT with Row_Number to display distinct values along with row numbers:

SELECT DISTINCT id, ROW_NUMBER() OVER (ORDER BY id) AS RowNum
FROM table
WHERE fid = 64
Copy after login

However, this query yielded only distinct values, similar to the following query:

SELECT distinct id FROM table WHERE fid = 64
Copy after login

To resolve this issue, the DENSE_RANK function can be used instead of Row_Number. DENSE_RANK assigns consecutive row numbers to distinct values, regardless of any gaps in the data.

Here's the corrected query:

SELECT distinct id, DENSE_RANK() OVER (ORDER BY  id) AS RowNum
FROM table
WHERE fid = 64
Copy after login

This query will provide the desired result: a list of distinct values with corresponding row numbers, as intended.

The above is the detailed content of How to Assign Row Numbers to Distinct Values in SQL?. 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