Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Top 10 Sales Every Month

Tags:

sql

statistics

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.

like image 712
DragonZelda Avatar asked Oct 21 '25 04:10

DragonZelda


1 Answers

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
like image 136
Oleg Dok Avatar answered Oct 23 '25 19:10

Oleg Dok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!