Question

I have a table named USER_ROLES in Oracle 10g as follows.

USER_ROLE_ID        USER_ID    AUTHORITY

28                  2          ROLE_ADMIN
45                  3          ROLE_USER
61                  3          ROLE_ASSISTANT
27                  3          ROLE_SUPERVISOR

Where USER_ID is a foreign key of the table USER_TABLE. I need to know a row number of a specific row from a group of rows associated with a specific user (USER_ID) (and not based on all the rows in this table).


The following SQL retrieves the row number for a given USER_ROLE_ID (28 in this case) based on all the rows in this table.

select row_num from 
(select row_number() over (order by user_role_id desc) as row_num, user_role_id 
from user_roles order by user_role_id desc)
where user_role_id=28

It displays 3, in this case.


But I need to retrieve the row number from a group of rows which is associated only with a particular user. For this to be so, if I try the following SQL,

select row_num from 
(select row_number() over (order by user_role_id desc) as row_num, user_role_id 
from user_roles order by user_role_id desc)
where user_id=2 and user_role_id=28

In this case, I have modified the WHERE clause from

where user_role_id=28

to

where user_id=2 and user_role_id=28

It gives the following error.

ORA-00904: "USER_ID": invalid identifier

So, what is the way to fetch a row number from only those rows which are associated with a specific user, in this scenario?

Was it helpful?

Solution

just add the user_id to the inner query. i think you also want to partition that analytic if you want the row_num to be per user_id (if not ignore that bit):

select row_num 
  from  (select row_number() over (partition by user_id 
                                   order by user_role_id desc) as row_num, 
                user_role_id, user_id
           from user_roles)
where user_role_id=28 and user_id = 2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top