我如何使用计数并取其平均值?

时间:2016-04-07 08:43:56

标签: sql sql-server count average sql-server-2014

我没有长时间解释这个问题,而只是展示我曾经尝试过的东西,顺便说一下,我正在使用Microsoft SQL Server 2014 - 12.0.2269.0(X64)并且正在使用Northwind;

select FirstName+' '+LastName Employee, count(ShipName) OrderQuantity, 
    case
        when count(ShipName)<50 then 'You're Fired!!!'
            when count(ShipName) between 50 and avg(count(ShipName))/count(FirstName) then 'Be Careful!'
    else 'You're the CEO Next Year'
    end Yorum
from Orders left join Employees
            on Employees.EmployeeID=Orders.EmployeeID
group by FirstName+' '+LastName
order by OrderQuantity

当我执行此查询时,我收到以下错误;

"Cannot perform an aggregate function on an expression containing an aggregate or a subquery."

我试图获得我分组的OrderQuantity列的平均值,我做错了什么?

3 个答案:

答案 0 :(得分:0)

可能你的问题是:

  • 分组由FirstName +&#39; &#39; +名字

你应该尝试先运行一个子查询,将这个联合First + Last Name作为一个字段,sql server无法确定FirstName +&#39; &#39; + LastName作为字段。尝试仅使用其中一个字段或

运行该组
  • 按FirstName,LastName分组(只是为了查看这是否是问题)

好吧,也许吧:

SELECT    fullname        employee , 
          Count(shipname) orderquantity , 
          CASE 
                    WHEN Count(shipname)<50 THEN 'You're fired!!!' when count(ShipName) between 50 and avg(count(ShipName))/count(EmployeeID) then 'be careful!' else 'you're the CEO Next Year' 
          END yorum 
FROM      orders 
LEFT JOIN 
          ( 
                 SELECT (firstname+' '+lastname) 'FullName', 
                        firstname, 
                        lastname, 
                        employeeid 
                 FROM   employees )tb1 
ON        tb1.employeeid == orders.employeeid 
GROUP BY  tb1.fullname 
ORDER BY  count(shipname) DESC

答案 1 :(得分:0)

COUNT(ShipName)只为该组返回一行,平均值没有意义。

AVG(COUNT(ShipName)) == COUNT(ShipName)

删除Avg(),它应该可以工作。您可以在结果集上使用avg()

检查以下链接可能有用

Why can't I perform an aggregate function on an expression containing an aggregate but I can do so by creating a new select statement around it?

答案 2 :(得分:0)

您似乎希望将AVGOVER子句一起使用:

WITH
CTE
AS
(
    select 
        FirstName+' '+LastName AS Employee
        ,count(ShipName) AS OrderQuantity
    from 
        Orders 
        left join Employees on Employees.EmployeeID = Orders.EmployeeID
    group by FirstName+' '+LastName
)
SELECT
    Employee
    ,OrderQuantity
    ,case
        when OrderQuantity < 50 then 'You are Fired!!!'
        when OrderQuantity between 50 and AVG(OrderQuantity) OVER() then 'Be Careful!'
        else 'You are the CEO Next Year'
    end AS Yorum
FROM CTE
order by OrderQuantity;

首先计算CTE中每位员工的COUNT。然后,您可以使用OrderQuantityAVG() OVER()与所有员工的全球订单平均值进行比较。