0

I have a query in SQL Server 2012:-

SELECT DISTINCT 
    FIELD_1, FIELD_2
FROM 
    TABLE_A

Now I want to get row number for each record. So I have used ROW_NUMBER() function for this purpose.

SELECT DISTINCT 
    ROW_NUMBER() OVER (ORDER BY FIELD_1, FIELD_2) AS rowId
    FIELD_1, FIELD_2
FROM 
    TABLE_A

This query does not give me distinct result.
How to retrieve distinct result with row number ?

shA.t
  • 16,580
  • 5
  • 54
  • 111
unknown
  • 4,859
  • 10
  • 44
  • 62

3 Answers3

3

When you are using DISTINCT you should not forget that it will apply after window functions like ROW_NUMBER that makes all your rows unique.

So try this:

SELECT 
    ROW_NUMBER() OVER (ORDER BY FIELD_1, FIELD_2) AS rowId,
    FIELD_1, FIELD_2
FROM 
    TABLE_A
GROUP BY
    FIELD_1, FIELD_2
shA.t
  • 16,580
  • 5
  • 54
  • 111
1

try to this

SELECT 
ROW_NUMBER() OVER (ORDER BY FIELD_1, FIELD_2) AS rowId
FIELD_1, FIELD_2
FROM (select DISTINCT FIELD_1, FIELD_2 TABLE_A ) a
Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32
  • 1
    I appreciate your answer, but sub-query will reduce performance of application. So I have to find any other way. – unknown Jun 15 '15 at 12:27
0

You are selecting DISTINCT ROW_NUMBER(). The row numbers will obviously be unique (e.g. distinct), so this won't really work for what you are trying to achieve.

Hysteria86
  • 367
  • 1
  • 10