1

我有两张表,我需要找到交付的包裹数量超过所有司机平均运送数量的司机,以及比平均数量多多少的司机。我显示的第一个表是 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

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

4

1 回答 1

1
    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_averageall_driver_counts

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

于 2013-10-22T03:46:58.020 回答