I have three tables and columns as below
resource: id, location.
subject: id, name
resource_subject: resource_id, subject_id
The relationship between "resource" and "subject" is many-to-many. Here is the query I have:
select r.* from resource r
inner join resource_subject subject on r.id = subject.resource_id
where (subject.subject_id= 2 or subject.subject_id= 4)
Queries as the above may produce duplicate records because one resource may belong to more than one subject. So, to remove the duplicates, I use distinct as the following:
select distinct r.* from resource r
inner join resource_subject subject on r.id = subject.resource_id
where (subject.subject_id= 2 or subject.subject_id= 4)
Now I want to do pagination of unique records. I read this SO post,
What is the best way to paginate results in SQL Server
I am interested in using ROW_NUMBER(). However, using ROW_NUMBER() would make duplicate records unique:
select distinct ROW_NUMBER() over( order by r.id asc) AS rownum, r.* from resource r
inner join resource_subject subject on r.id = subject.resource_id
where (subject.subject_id= 2 or subject.subject_id= 4)
How can I do ROW_NUMBER() over records after "distinct"?