Home > Database > Mysql Tutorial > How to Display Row Numbers for Unique Values in SQL?

How to Display Row Numbers for Unique Values in SQL?

Patricia Arquette
Release: 2024-12-25 18:17:11
Original
128 people have browsed it

How to Display Row Numbers for Unique Values in SQL?

Displaying Row Numbers of Unique Values using SQL

The DISTINCT keyword in SQL is used to retrieve only unique values from a specified column. In this particular case, you aim to display the row numbers of unique values in a column using the ROW_NUMBER() function.

However, the query you provided:

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

is not returning the expected results because it effectively eliminates duplicates using DISTINCT. As a result, it behaves similarly to the following query:

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

To achieve your desired output, you can utilize the DENSE_RANK() function instead. DENSE_RANK() assigns unique row numbers to each distinct value in the specified order, even if there are duplicate values.

Here's the modified query:

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

This query will provide you with the row numbers corresponding to the unique values in the specified column for the rows satisfying the condition WHERE fid = 64.

The above is the detailed content of How to Display Row Numbers for Unique 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