Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion Groups
DB Engine
SQL ServerMSDESQL Server CE
Services
Analysis (Data Mining)Analysis (OLAP)DTSIntegration ServicesNotification ServicesReporting Services
Programming
CLRConnectivitySQLXML
Other Technologies
ClusteringEnglish QueryFull-Text SearchReplicationService Broker
General
Data WarehousingPerformanceSecuritySetupSQL Server ToolsOther SQL Server Topics
DirectoryUser Groups
Related Topics
MS AccessOther DB ProductsMS Server Products.NET DevelopmentVB DevelopmentJava DevelopmentMore Topics ...

SQL Server Forum / DB Engine / SQL Server / June 2008

Tip: Looking for answers? Try searching our database.

Selectint Top N within a group

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
mar - 29 Jun 2008 08:28 GMT
I have a table that looks like this:

ACCOUNT    ID    DATE
aaa        01/01/08
aaa        02/01/08
aaa        03/01/08
aaa        04/01/08
bbb        02/01/08
bbb        03/01/08
bbb        04/01/08
bbb        05/01/08

I need a query that sorts it by  ACCOUNTID then by DATE in descending
order and then only returns the top 3 for each account.  It would
return the following:

ACCOUNT    ID    DATE    NUMBER
aaa        04/01/08    1
aaa        03/01/08    2
aaa        02/01/08    3
bbb        05/01/08    1
bbb        04/01/08    2
bbb        03/01/08    3

Help?

Thanks.
Uri Dimant - 29 Jun 2008 08:41 GMT
mar
with cte

as

(

select * ,row_number()

over (partition by account order by datename desc)as r

from #t

) select * from cte where r<=3

>I have a table that looks like this:
>
[quoted text clipped - 23 lines]
>
> Thanks.
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.