sql分组查找平均值

时间:2016-11-09 16:14:37

标签: mysql sql

我希望找到每个订单总费用的平均费用,但我的分组功能无效

SELECT AVG(SUM(quantityOrdered*priceEach)) AS total 
FROM orderdetails od 
GROUP BY orderNumber
下面的

是我的数据库的片段

orderNumber productCode quantityOrdered priceEach orderLineNumber
10100       S24_3969                 49     35.29               1
10101       S18_2325                 25    108.06               4
10101       S18_2795                 26    167.06               1
10101       S24_1937                 45     32.53               3
10101       S24_2022                 46     44.35               2
10102       S18_1342                 39     95.55               2
10102       S18_1367                 41     43.13               1
10103       S10_1949                 26    214.3               11
10103       S10_4962                 42    119.67               4
10103       S12_1666                 27    121.64               8
10103       S18_1097                 35     94.5               10
10103       S18_2432                 22     58.34               2
10103       S18_2949                 27     92.19              12
10103       S18_2957                 35     61.84              14
10103       S18_3136                 25     86.92              13
10103       S18_3320                 46     86.31              16

3 个答案:

答案 0 :(得分:0)

无效使用不能同时使用两个聚合函数

    SELECT SUM(quantityOrdered*priceEach) AS total
    FROM orderdetails od 
    GROUP BY orderNumber
    Having  SUM(quantityOrdered*priceEach)>(SELECT  AVG(quantityOrdered*priceEach) FROM orderdetails)

答案 1 :(得分:0)

你分两步完成。

<强> SQL Fiddle Demo

  • 计算每个订单的总和。

    SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total 
    FROM orderdetails od 
    GROUP BY orderNumber
    
  • 计算所有总数之间的平均值

    SELECT AVG(total)
    FROM ( SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total 
           FROM orderdetails od 
           GROUP BY orderNumber
         ) T
    

编辑:在检查Ritesh答案后,我想念最后一步。

SELECT o.*, t.global_avg
FROM (SELECT orderNumber, SUM(quantityOrdered*priceEach) AS order_total 
      FROM orderdetails od 
      GROUP BY orderNumber) o
CROSS JOIN       
     (SELECT AVG(total) global_avg
      FROM ( SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total 
             FROM orderdetails od 
             GROUP BY orderNumber
            ) t
      ) t
WHERE o.order_total > t.global_avg;

<强>输出:

enter image description here

答案 2 :(得分:0)

只需使用sum()除以数字来计算平均值:

SELECT SUM(quantityOrdered*priceEach) / COUNT(DISTINCT orderNumber) AS total 
FROM orderdetails od ;