选择值<&lt;的记录avg() - 不正确的结果

时间:2015-02-23 20:21:09

标签: sql sql-server average

我在NORTHWND db上做了一些基本的练习。我想执行以下代码:

SELECT        
    sum(SaleAmount) AS SaleAmount
    , CompanyName

FROM      [Sales Totals by Amount]

where [SaleAmount] > 
(
        Select
        avg(SaleAmount) as SaleAmount
        from [Sales Totals by Amount]
)
group by CompanyName

平均值等于4409,4948。当我试图获得大于平均值的值时,结果是正确的。当我试图获得低于平均值的值时,它会返回低于和高于平均值的值。 如果你指出我的错误在哪里,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

要将过滤器应用于聚合公式,请使用HAVING关键字:

SELECT        
    SUM(SaleAmount) AS SaleAmount,
    CompanyName
FROM      [Sales Totals by Amount]
GROUP BY CompanyName
HAVING sum(SaleAmount)  > 
(
        Select
        AVG(SaleAmount) as SaleAmount
        FROM [Sales Totals by Amount]
)

答案 1 :(得分:0)

您也可以使用CTE解决此问题:

;WITH TotalSalesByCompany AS (
    SELECT SUM(SaleAmount) AS TotalSaleAmount,
           CompanyName
      FROM [Sales Totals by Amount]
     GROUP BY CompanyName
)
SELECT * 
  FROM TotalSalesByCompany
 WHERE [TotalSalesAmount] > 
       (SELECT AVG(SalesAmount) AS AverageSales FROM [Sales Totals By Amount])

CTE按公司生成总计清单,SELECT子句选择总销售额大于平均值的每家公司。