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.
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 KeyPERIOD smallint 2 Primary KeyYEAR smallint 2 Primary KeySALES numeric 9What 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), etcorID, SALES, YEAR, RANKWould 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, YearUsing the above twice is one way to get your answer:SELECT Year, COUNT(*) as Rank, ID, TotalSalesFROM (above SQL) AINNER JOIN (above SQL) BON A.ID = B.ID AND A.Year = B.Year ANDA.TotalSales >= B.TotalSalesGROUP BY A.ID, A.Year, A.TotalSalesORDER 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 |
 |
|
|
|
|
|
|