Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi,Pretty new to SQL here. I have a table that includes Region (1-10), Month, Member ID, and multiple transactions per member (which will be sum of paid). I'd like to extract the top 5 sum of paid amounts....by region, by month, by member. So the resulting query will have 50 results per month (top 5 for each region each month). I've tried in vain to mimic some code I've found online, so any help/input/advice would be very, very much appreciated.Thank you all.Joe
James K
Master Smack Fu Yak Hacker
3873 Posts
Posted - 2014-03-31 : 15:29:12
You can use the row_number function with appropriate partitioning and ordering clauses - for example:
;WITH cte AS( SELECT *, ROW_NUMBER() OVER (PARTITION BY region, MONTH, member ORDER BY amount DESC) AS RN FROM YourTable) SELECT * FROM cte WHERE RN <= 5;