Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Top three records for each cusip

Author  Topic 

gwguy7
Starting Member

3 Posts

Posted - 2011-07-07 : 09:42:44

I need some help for formulating this query:

Currently I have a query which pulls data from 2-3 tables for the cusips that I asked for. The data looks like this:

Cusip Price Data_entered
aa1 101.1 05/06
aa1 100.2 05/03
aa1 99.2 05/02
aa1 102.2 04/25
ba1 45.5 06/01
ba1 46.8 05/25
ba1 43.0 05/20
ba1 42.0 05/15

I want to further pull only three latest records for each cusips from this dataset. So the output will look like:


aa1 101.1 05/06
aa1 100.2 05/03
aa1 99.2 05/02
ba1 45.5 06/01
ba1 46.8 05/25
ba1 43.0 05/20

Can someone help me with this? For some reason the "top" keyword doesnt work in the sql tool that I use.

Thanks !!

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-07-07 : 09:48:34
select * from
(
select *, seq = row_number() over (partition by cusip order by data_entered desc)
)
where seq <= 3
order by cusip, data_entered

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

gwguy7
Starting Member

3 Posts

Posted - 2011-07-07 : 10:42:42
For some reason the "row_number() over (partition by cusip order by data_entered desc)" doesnt work for me.


This is how I used your query:

-----
select cusip,rownum over
-------

Right now I get only 3 records for one cusip. I have to somehow get to use the partition clause. Any ideas?





Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-07-07 : 11:17:52
Are you using sql server?
Which version?

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-07-08 : 04:22:35
If the version is lower than 2005, try first two methods
http://beyondrelational.com/blogs/madhivanan/archive/2008/09/12/return-top-n-rows.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -