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.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Add a rank per year in a query that crosses multiple years
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

AskSQLTeam
Ask SQLTeam Question

USA
0 Posts

Posted - 12/05/2002 :  07:47:19  Show Profile  Visit AskSQLTeam's Homepage  Reply with Quote
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

USA
7423 Posts

Posted - 12/05/2002 :  08:15:31  Show Profile  Visit jsmith8858's Homepage  Reply with Quote
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
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2019 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000