Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

Row_number() not working when distinct the query.

For Example,

I have 400 Records in my table. In that Records some duplicates are avaliable.

When i distinct i got only 4 Rows. (This is correct)

But, when i use the same query in addition to add one column "Row_number() OVER(PARTITION BY RoleCode ORDER BY ID AS [Sl.No]" distinct not working. it will show all 400 Records.

See my Query (Before Row_Number())
-----------------------------------
select distinct ID,RoleCode,projcode from tab1 where rolecode='ALE' and projcode='268'

Output
------
ID RoleCode ProjCode
1266 ALE 268
1347 ALE 268
1408 ALE 268
1420 ALE 268

Same Query After using Row_Number() --> Distinct not working and shows all values
-------------------------------
select distinct ID,RoleCode,projcode,Row_number() OVER(PARTITION BY rolecode ORDER BY ID) AS [Sl.No] from tab1 where rolecode='ALE' and projcode='268'


TranID RoleCode ProjCode Sl.No
1266 ALE 268 1
1266 ALE 268 2
1266 ALE 268 3
1266 ALE 268 4
1266 ALE 268 5
1266 ALE 268 6
1266 ALE 268 7
1266 ALE 268 8
1266 ALE 268 9
1266 ALE 268 10
1266 ALE 268 11
1266 ALE 268 12
1266 ALE 268 13
1266 ALE 268 14
1266 ALE 268 15
1266 ALE 268 16
---- --- --- --
---- --- --- --

400 Rows Affected

What is the problem and why distinct not working when using Row_number() in SQL Query...?
Posted
Comments
Amir Mahfoozi 31-Oct-11 14:00pm    
What was the result ?

1 solution

Try this one :

SQL
select * , Row_number() OVER(PARTITION BY rolecode ORDER BY ID) AS [Sl.No] from
( 
   select distinct ID,RoleCode,projcode from tab1 where rolecode='ALE' and projcode='268'
) as s
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900