选择大于平均值的值

时间:2013-10-22 01:24:19

标签: mysql sql join count sum

我有两张牌桌,我需要找到的牌头数超过了所有牌手所承载的平均票数以及更多的平均值。我要显示的第一个表是Package表,第二个表是Truck表。我知道我需要使用计数,但我无法弄清楚如何将其与平均值

结合起来
Truck_no
103 
105 
102 
108 
108 
108 
101 
109 
109 
100 
100 
100 


Truck_no Drivername
100 JONES
101 DAVIS
102 GOMEZ
103 THOMPSON
104 HERSHEY
105 FERRIS
106 SHAVER
107 LEE
108 TOPI
109 ACKERMAN

到目前为止这是我的查询

select drivername, count(package.truck_no) as PackageCount
from PACKAGE, truck
where truck.TRUCK_NO=PACKAGE.TRUCK_NO
group by drivername

我得到了这些结果

Drivername      Packagecount
ACKERMAN    2
DAVIS           1
FERRIS          1
GOMEZ           1
JONES           3
THOMPSON    1
TOPI            3

我真的很感激任何帮助。非常感谢

1 个答案:

答案 0 :(得分:0)

    SELECT drivername, packagecount
      FROM (   SELECT drivername, COUNT(1) AS packagecount
                 FROM truck
            LEFT JOIN package
                      ON truck.truck_no = package.truck_no
             GROUP BY 1) all_driver_counts
CROSS JOIN
           (SELECT AVG(n) AS avg_packagecount
              FROM (  SELECT truck_no, COUNT(1) AS n
                        FROM package
                    GROUP BY 1) truck_packages) the_average
     WHERE packagecount > avg_packagecount;

这会产生:

+------------+--------------+
| drivername | packagecount |
+------------+--------------+
| ACKERMAN   |            2 |
| JONES      |            3 |
| TOPI       |            3 |
+------------+--------------+

自下而上阅读上面的查询,我们计算每辆卡车交付的平均包裹数(the_average),并将其与每个驱动程序的计数(all_driver_counts)连接起来,仅筛选那些驱动程序数超过的行数平均值。

Analytic(SQL滑动窗口)函数可能使上述查询更容易,但是,唉,MySQL不支持它们。