Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql query distinct with Row_Number

Tags:

sql

distinct

I am fighting with the distinct keyword in sql. I just want to display all row numbers of unique (distinct) values in a column & so I tried:

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

however the below code giving me the distinct values:

SELECT distinct id FROM table WHERE fid = 64 

but when tried it with Row_Number.
then it is not working.

like image 298
objectWithoutClass Avatar asked Aug 08 '13 08:08

objectWithoutClass


People also ask

Is row number unique?

ROW_NUMBER adds a unique incrementing number to the results grid. The order, in which the row numbers are applied, is determined by the ORDER BY expression.

Is distinct faster than ROW_NUMBER?

In my experience, an aggregate (DISTINCT or GROUP BY) can be quicker then a ROW_NUMBER() approach. Saying that, ROW_NUMBER is better with SQL Server 2008 than SQL Server 2005. However, you'll have to try for your situation.

Can I use distinct * in SQL?

The SQL SELECT DISTINCT StatementThe SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Does distinct return the first row?

Bare usage of DISTINCT will return the first occurrence. However, it can work either way by sorting the initial results first before conducting the distinction step.


1 Answers

This can be done very simple, you were pretty close already

SELECT distinct id, DENSE_RANK() OVER (ORDER BY  id) AS RowNum FROM table WHERE fid = 64 
like image 64
t-clausen.dk Avatar answered Sep 22 '22 15:09

t-clausen.dk