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,i have something similar to this:SELECT TOP 10 OrderType, CustomerFROM MyTableWHERE OrderType = 'Apples'ORDER BY OrderValue DescUNIONSELECT TOP 10 OrderType, CustomerFROM MyTableWHERE OrderType = 'Oranges'ORDER BY OrderValue DescUNIONSELECT TOP 10 OrderType, CustomerFROM MyTableWHERE OrderType = 'Bananas'ORDER BY OrderValue DescUNIONetc...How would you replace the unions with a single loop looking at OrderType as a variable?The values for OrderType criteria could be in a string if possible or in a separate table. We are talking about 10 to 20 different variables that the code will need to go through.Note that i've never used while loop, for each etc. in tsql before...i'm on sql server 2008.make sense?thanks
James K
Master Smack Fu Yak Hacker
3873 Posts
Posted - 2013-10-07 : 10:10:13
You could do the following:
WITH cte AS ( SELECT ordertype , customer , ROW_NUMBER() OVER ( PARTITION BY ordertype, customer ORDER BY ordervalue DESC ) AS RN ) SELECT ordertype , customer FROM cte WHERE RN <= 10;
If you want with ties, replace the row_number function with RANK. Another way would be to use a cross apply, but this is probably more efficent.