The task is to select the sub category with the minimum profit per year.
The next query, selects few sub categories per year:
select
min (Profit),
CalendarYear,
EnglishProductSubcategoryName
from (
select
SUM(fis.SalesAmount-fis.TotalProductCost) Profit,
t.CalendarYear,
sc.EnglishProductSubCategoryName
from FactInternetSales fis
inner join DimProduct p
on fis.ProductKey = p.ProductKey
inner join DimProductSubcategory sc
on p.ProductSubcategoryKey = sc.ProductSubcategoryKey
inner join DimTime t
on fis.DueDateKey = t.TimeKey
group by CalendarYear, EnglishProductSubcategoryName) aa
--Order by CalendarYear
) aa
group by CalendarYear, EnglishProductSubcategoryName
order by CalendarYear
If you want to find the category with the minimum profit for a given year, you need to rewrite your query:
This will find the row(s) – it could be multiple – that have the minimum profit (for 2011) as reported back by the subquery.
Update: since you need the minimum profit for every year, I would probably totally rewrite this query to something like:
This uses a CTE (Common Table Expression) and the
ROW_NUMBER()ranking function – both available in SQL Server 2005 and newer (you didn’t mention your version in your question)