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.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Add a rank per year in a query that crosses multiple years

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-12-05 : 07:47:19
Mark writes "I have a table which contains summary sales data in a single data table.

A simplified version of the table is as follows:

ID char 15 Primary Key
PERIOD smallint 2 Primary Key
YEAR smallint 2 Primary Key
SALES numeric 9

What I would like to accomplish is to sum the SALES field by YEAR and ID, and display the ID's rank based on SALES against the other ID's for that given year, but not as an overall rank across all years.

Preferably I would like to avoid using a temp table, but it may not be possible.

I considered using nested queries with a SELECT COUNT as in article http://www.sqlteam.com/item.asp?ItemID=1491 but it would require a nested query for each year, which I think will work, but it's a bit messy if many years are required.

Output format doesn't especially matter as I will use the query in a report application, so either:

ID,SALES(YEAR1),RANK(YEAR1),SALES(YEAR2),RANK(YEAR2), etc

or

ID, SALES, YEAR, RANK

Would work.

Thanks!"

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2002-12-05 : 08:15:31
First, you need total sales by year by ID:

SELECT ID, Year, SUM(Sales) as TotalSales FROM Sales GROUP BY ID, Year


Using the above twice is one way to get your answer:

SELECT Year, COUNT(*) as Rank, ID, TotalSales
FROM (above SQL) A
INNER JOIN (above SQL) B
ON A.ID = B.ID AND
A.Year = B.Year AND
A.TotalSales >= B.TotalSales
GROUP BY A.ID, A.Year, A.TotalSales
ORDER BY A.Year, COUNT(*)

I'm sure others will pipe in with other options, but if the table isn't too big and this works fine, i think it's the easiest and most common way to handle this type of query.


- Jeff
Go to Top of Page
   

- Advertisement -