We'll tackle it in 3 stages:
- First get the total sales for each sales person
- Next wrap this query up in a common table expression
- Query your common table expression using a Top clause
-- First group the sales by sales person
select p.FirstName + ' ' + p.LastName as SalesPerson, sum(o.TotalDue)as TotalSales
from sales.SalesOrderHeader as o
join person.Person as p on p.BusinessEntityID = o.SalesPersonID
group by p.FirstName + ' ' + p.LastName
-- Next wrap the grouped sales into a common table expression which you can now query
with GroupedSales
as
(
select p.FirstName + ' ' + p.LastName as SalesPerson, sum(o.TotalDue)as TotalSales
from sales.SalesOrderHeader as o
join person.Person as p on p.BusinessEntityID = o.SalesPersonID
group by p.FirstName + ' ' + p.LastName
)
select SalesPerson, TotalSales
from groupedsales
-- Finally add a top statement
with GroupedSales
as
(
select p.FirstName + ' ' + p.LastName as SalesPerson, sum(o.TotalDue)as TotalSales
from sales.SalesOrderHeader as o
join person.Person as p on p.BusinessEntityID = o.SalesPersonID
group by p.FirstName + ' ' + p.LastName
)
select Top(3) SalesPerson, TotalSales
from GroupedSales
order by TotalSales desc
No comments:
Post a Comment