SQL GROUP BY查询问题

时间:2014-01-09 22:25:38

标签: mysql sql

我有一个包含以下列的表:

DriverNumber; DriverName; CarNumber; DriverConditions; LogonTime; VehicleID

此表为每个DriverNumber的每个LogonTime都有一个条目,并且驱动程序可以登录到不同的车辆。

例如:

93070495    Mehar   189 Parcel, V, Wheelchair, M50, Special, Animal, COD P...       Jan  2 2014 07:40:26:197AM  1029
93070495    Mehar   189 Parcel, V, Wheelchair, M50, Special, Animal, COD P...       Jan  7 2014 08:09:50:097AM  1029
25184313    Kerry   895 Parcel, Cheques, V, Wheelchair, Special, Animal, C...       Jan  3 2014 05:00:26:600PM  970

我本来想要做的是显示DriverNumber登录每辆车的次数。

这是我到目前为止所做的:

SELECT DriverNumber, DriverName, CarNumber, DriverConditions, LogonTime, 
    count(DriverNumber) as DriverCount 
FROM SilverDrivers 
WHERE DriverNumber > 0
GROUP BY CarNumber

这让我接近我所追求的,但它只显示每个DriverNumber一个CarNumber。例如:

DRIVER HDL | DRIVER NAME | CAR NUMBER | DRIVER CONDITIONS | NUMBER OF LOGONS
98749492   | Manpreet    | 3          | Parcel            | 10
32176467   | Mark        | 19         | Wheelchair        | 7
92173581   | Varinder    | 46         | Parcel            | 1

我希望它看起来像是:

DRIVER HDL | DRIVER NAME | CAR NUMBER | DRIVER CONDITIONS | NUMBER OF LOGONS
98749492   | Manpreet    | 3          | Parcel            | 7
98749492   | Manpreet    | 12         | Parcel            | 3
32176467   | Mark        | 19         | Wheelchair        | 4
32176467   | Mark        | 214        | Wheelchair        | 3
92173581   | Varinder    | 46         | Parcel            | 1

2 个答案:

答案 0 :(得分:7)

您还应按驱动程序编号分组以获得所需的计数。另外,将所有其他列添加到您的GROUP BY子句中,并删除SELECT中不唯一的列(我只留下DriverName,因为我认为它对于DriverNumber总是相同的SELECT DriverNumber, DriverName, CarNumber, count(*) as DriverCount FROM SilverDrivers WHERE DriverNumber > 0 GROUP BY DriverNumber, DriverName, CarNumber 1}})。

{{1}}

答案 1 :(得分:-5)

你想要

GROUP BY DriverNumber, CarNumber

GROUP BY CarNumber, DriverNumber