Question

I am using custom paging in my application so each time i fetch latest 10 records from my Database and displayed on my app.

My problem is

I want to fetch latest user information on top.

While fetching information each user have more than one rows so i use dense_rank function for grouping those records.

for example

RRowNo   UserID  Location  CreatedOn

1       Avsih     Delhi       06-02-2014
1       Avsih     Mumbai      06-02-2014
1       Avsih     Kerala      06-02-2014
2       Nimmi     UP          06-02-2014
3       Rahul1    Delhi       06-02-2014
4       Rahul2    Mumbai      06-02-2014
5       Rahul3    Kerala      06-02-2014
6       Rahul4    UP          06-02-2014
7       Rahul5    Delhi       06-02-2014
8       Rahul6    Mumbai      06-02-2014
9       Rahul7    Kerala      06-02-2014
10      Rahul8    UP          06-02-2014
11      Rahul9    UP          07-02-2014

Consider my table name is emp

My query is

select * 
from (
   select dense_rank() over (order by userid asc) as rowno,
   from emp
) as tab 
where rowno>='1' and rowno<='10'
order by Createdon desc

Rahul9 is my latest record (ie createdon must be 07/02/2014) i want that record to be top most.But by using that query i cant fetch so please help how to modify this query.

Was it helpful?

Solution

I think you want the users with the most recent createdon first. Assuming createon is the same for all users, try:

select * 
from (select dense_rank() over (order by createdon desc, userid asc) as rowno
      from emp
     ) tab 
where rowno >= 1 and rowno <= 10
order by Createdon desc;

OTHER TIPS

A sub query such as

select * from ( select dense_rank() over (order by userid asc) as rowno, * from emp
inner join (select userid,MAX(CreatedOn) AS MaxCreatedOn FROM emp GROUP BY userid) a ON a.userid = emp.userid
) as tab where rowno>='1' and rowno<='10' order by a.MaxCreatedon desc

Where you are getting the most recent date per user and then joining to that might do the trick?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top