Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
with SALES1 as
(
select SalesPerson,State,sum(Cost) Tot_Cost
from InvoiceTable
group by SalesPerson,State
),
SALES2 as
(
select SalesPerson,State, row_number() over(partition by State order by Tot_Cost desc) t_rank
from SALES1
)
select SalesPerson,State,Tot_Cost
from SALES2
where t_rank in (1,2,3,4,5)
Try having a go yourself and pasting your attempts here if you do not get what you are looking for. People will be glad to help you, but they do not want to do your work for you.Would someone mind helping me out on that by posting the query that I would use?
SET NOCOUNT ON
Declare @Sums
Table (RowId Int Identity(1,1),
Rank Int,
SalesPerson VarChar(20),
State VarChar(20),
SumOfCost Numeric(10,4)
Primary Key (State, SumOfCost, SalesPerson))
Insert Into @Sums(SalesPerson, State, SumOfCost)
Select SalesPerson, State, Sum(Cost)
from InvoiceTable
Group By SalesPerson, State
Order By State, Sum(Cost) DESC
Update @Sums
Set Rank = RowId - MinRowId + 1
From @Sums S
Inner Join (
Select State, Min(RowId) As MinRowId
From @Sums
Group By State
) as A
On S.State = A.State
Select State, SalesPerson, SumOfCost
From @Sums
Where Rank <= 5
Order BY State, SumOfCost DESC