MIN函数在SQL复杂查询中无法正常工作

时间:2012-12-09 09:15:59

标签: sql sql-server

任务是选择每年最低利润的子类别。 下一个查询,每年选择几个子类别:

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 

1 个答案:

答案 0 :(得分:1)

如果您想查找给定年份的最低利润类别,则需要重写您的查询:

select 
    Profit,
    CalendarYear, 
    EnglishProductSubcategoryName
from 
    (..... ) aa
where
    CalendarYear = 2011
    AND Profit = (SELECT MIN(Profit) FROM aa WHERE aa.CalendarYear = 2011)

这将找到行(s) - 它可能是多个 - 具有子查询报告的最小利润(2011年)。

更新,因为您需要每年的最低利润,我可能会完全将此查询重写为:

;WITH YearlyProfitsByCategory AS
(
   SELECT
      SUM(fis.SalesAmount - fis.TotalProductCost) Profit, 
      t.CalendarYear, 
      sc.EnglishProductSubCategoryName
   FROM
      dbo.FactInternetSales fis 
   INNER JOIN
      dbo.DimProduct p ON fis.ProductKey = p.ProductKey
   INNER JOIN
      dbo.DimProductSubcategory sc ON p.ProductSubcategoryKey = sc.ProductSubcategoryKey
   INNER JOIN
      dbo.DimTime t ON fis.DueDateKey = t.TimeKey
   GROUP BY
      t.CalendarYear, 
      sc.EnglishProductSubCategoryName
),
YearlyMinProfits AS 
(
    SELECT
       CalendarYear, 
       EnglishProductSubCategoryName,
       Profit,
       RowNum = ROW_NUMBER() OVER (PARTITION BY CalendarYear ORDER BY Profit)
    FROM YearlyProfitsByCategory 
)
SELECT 
   CalendarYear, EnglishProductSubCategoryName, Profit
FROM YearlyMinProfits
WHERE RowNum = 1  -- the row with the smallest profit, for every year

这使用CTE(公用表表达式)和ROW_NUMBER()排名功能 - 两者都可用于SQL Server 2005 和更新版本(您未在提问中提及您的版本)< / p>