返回高于平均值的行

时间:2017-07-17 15:48:21

标签: sql count average

我试图找到订单数量高于平均值的国家/地区。这是我得到的。问题是(见图)每个国家的订单数量都是关闭的,因为每个国家的订单数量应该不同

  SELECT avg(NumberOrders) as avg, 
         Customers.Country, 
         NumberOrders
    FROM Customers,
          (SELECT COUNT(Orders.OrderId) AS NumberOrders 
             FROM Customers JOIN 
                  Orders ON Customers.CustomerID = Orders.CustomerID
         GROUP BY Customers.Country) nested
GROUP BY Customers.Country
  HAVING NumberOrders > avg;

Output

1 个答案:

答案 0 :(得分:1)

如果你的DBMS支持 Windowed Aggregates (几乎除了MySQL和访问之外):

select *
from
 (
   SELECT Customers.Country, 
      COUNT(Orders.OrderId) AS NumberOrders,  -- count per country
      AVG(COUNT(Orders.OrderId)) OVER () AS avgOrders -- average count
   FROM Customers
   JOIN Orders 
     ON Customers.CustomerID = Orders.CustomerID
   GROUP BY Customers.Country
 ) nested
WHERE NumberOrders > avgOrders

编辑:

对于不支持窗口聚合的DBMS,它的方式更复杂:

SELECT Customers.Country, 
   COUNT(Orders.OrderId) AS NumberOrders  -- count per country
FROM Customers
JOIN Orders 
  ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.Country
HAVING COUNT(Orders.OrderId) >
 ( select avg(NumberOrders)
   from
    (
      SELECT Customers.Country, 
         COUNT(Orders.OrderId) AS NumberOrders  -- count per country
      FROM Customers
      JOIN Orders 
        ON Customers.CustomerID = Orders.CustomerID
      GROUP BY Customers.Country
    ) AS dt
 )

如果DBMS支持公用表表达式,则可以简化:

with cte as
 (
   SELECT Customers.Country, 
      COUNT(Orders.OrderId) AS NumberOrders  -- count per country
   FROM Customers
   JOIN Orders 
     ON Customers.CustomerID = Orders.CustomerID
   GROUP BY Customers.Country
 ) 
select *
from cte
WHERE NumberOrders >
 (
   select avg(NumberOrders) from cte
 )