Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Top 10 -- with a twist.

Status
Not open for further replies.

markinro

IS-IT--Management
Mar 27, 2002
25
US
Ok, all you gurus, try this one. I am generating a top 10 revenue report in the following manner.

For each month in the past year...
INSERT INTO #topcust
SELECT TOP 10 customer FROM REVENUES
WHERE DATEDIFF(m,sales_date,GETDATE())=0 --this month
GROUP BY customer
ORDER BY SUM(amount) DESC
..rinse and repeat for months 1 thru 11

Anyone have a way to run this in a single statement ?

(#topcust has a unique index for custnbr so this results in a list of customers who have been in the top 10 for any of the past 12 months. This way, we can trend our top customers.)

 
may be something like:

for i = 1 to 11
INSERT INTO #topcust
SELECT TOP 10 customer FROM REVENUES
WHERE month(sales_date)=i and year(sales_date)= year (getdate())
GROUP BY customer
ORDER BY SUM(amount) DESC
 
Code:
INSERT INTO #topcust
select customer from revenues as q
where customer in (
SELECT TOP 10 customer FROM REVENUES
WHERE DATEDIFF(m,sales_date,q.sales_date)=0
Group by customer
ORDER BY SUM(amount) DESC )
where datediff(m,sales_date,getdate()) <= 11
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top