Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a History Table tbl_history which contains crores of Records.

Table Sample Data:-
id Volume DeletedTime
1  C      11am 
1  C      12am 
1  C      1pm 
1  C      2pm 
1  C      3pm 
1  D      11am 
1  D      12am 
1  D      1pm 
1  D      2pm 
1  D      3pm 
2  C      11am 
2  C      12am 
2  C      1pm 
2  C      2pm 
2  C      3pm 
2  D      11am 
2  D      12am 
2  D      1pm 
2  D      2pm 
2  D      3pm 

Now what i want is to list out last 3 Records per ID and per Category i.e in our Case Volume, without using Row number function the reason i am looking to implement some other logic other than Row_number() because query takes long time to execute.

Expected Output:-
id  Volume  DeletedTime
1   C       01:00:00 PM
1   C       02:00:00 PM
1   C       03:00:00 PM
1   D       01:00:00 PM
1   D       02:00:00 PM
1   D       03:00:00 PM
2   C       01:00:00 PM
2   C       02:00:00 PM
2   C       03:00:00 PM
2   D       01:00:00 PM
2   D       02:00:00 PM
2   D       03:00:00 PM


Please help me out.

Regards,
Girish
Posted
Updated 23-Feb-12 3:34am
v2
Comments
Herman<T>.Instance 23-Feb-12 9:43am    
how many rows data and how are indexes setup on that table?
GirishChhatani1 23-Feb-12 9:49am    
Table have around 1 crore of data and Clustered index is created on ID Column.
ZurdoDev 23-Feb-12 10:15am    
It is likely slow because of indexing. I use Row_Number all the time. You'll have to group and use nested queries with ORDER BY DESC and top 3.
GirishChhatani1 23-Feb-12 10:33am    
i tried but still it doesn't work.

select top 3 ID,Volume,MAX(DeletedTime) as MaxDeletedTime from tbl_History with(nolock)
group by ID,Volume
order by MAX(DeletedTime) desc
Ganesan Senthilvel 23-Feb-12 11:26am    
SELECT column1,column2 ,...,columnn FROM

(SELECT rownum a, column1,column2 ,...,columnnFROM table_name)

WHERE a > ( SELECT (max(rownum)-N)FROM table_name)

1 solution

If the query works and you think it is slow, try indexing the columns that are being queried and joined. ROW_NUMBER is not slow, it is how you use it that makes it slow.
 
Share this answer
 
Comments
GirishChhatani1 27-Feb-12 5:39am    
Hello Shameel,
I have created Clustered index on id column.There are 1 Crore records in a table.
[no name] 27-Feb-12 6:02am    
Try creating indexes on the other two columns as well. Alternatively include the volume column in the id column index using the INCLUDE clause.

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