Greeting all. I have a SQL 2008 express database, lets name is tbl_Merchant, similar as following:
Merchant | Sales | Month Comp.1 100 1 Comp.2 230 1 Comp.3 120 1 Comp.1 200 2 Comp.2 130 2 Comp.3 240 2 Comp.1 250 3 . . . . . . . . .
I need to find the top 10 merchant with sales every month over 12 months.
It is very easy if it is just one month.
SELECT TOP 10 Merchant, Sales, Month FROM tbl_Merchant WHERE Month = 1 ORDER BY Sales DESC
But I am stuck if I wan to find them over 12 months. I need to display 120 merchants, which are top 10 sales merchant of each month. Currently my solution is to union 12 tables from month 1 to 12 together but I don’t think it is a good way.
Can any one kindly give me any suggestion?
Thank you very much.
Advertisement
Answer
Valid for Sql Server 2005+
Try this for overall:
SELECT TOP 10 Merchant, SUM(Sales) Sales FROM tbl_Merchant WHERE Month BETWEEN 1 and 12 GROUP BY Merchant ORDER BY 2 DESC
OR
if you need details per month for top 10 PER MONTH
;WITH MonthsCTE(m) as ( SELECT 1 m UNION ALL SELECT m+1 FROM MonthsCTE WHERE m < 12 ) SELECT m [Month], t.* FROM MonthsCTE CROSS APPLY ( SELECT TOP 10 Merchant, SUM(Sales) Sales FROM tbl_Merchant WHERE Month = MonthsCTE.m GROUP BY Merchant ORDER BY 2 DESC ) t