我正在尝试处理我的数据库中的以下数据,以返回给定时间戳的给定车辆(在本例中为“Car 1”)的唯一驱动程序。这是一个组成的例子,但应该足够了。
我的代码到目前为止 - 哪个不太符合我的要求:
USE
VehicleUse
SELECT
DISTINCT((CONVERT(VARCHAR, m.CurrentDateTime,20) + ' ' + v.VehicleName + ' ' + m.Driver)) AS [Unique Combo]
, count(m.CurrentDateTime)
FROM
Vehicles AS v INNER JOIN
MainData AS m
ON l.VehicleID = m.VehicleID
WHERE
v.VehicleName = 'Car 1'
GROUP BY
m.CurrentDateTime
, v.VehicleName
, m.Driver
ORDER BY
[Unique Combo]
示例:预处理
+---------------------+---------+--------+ | Date Time | Vehicle | Driver | +---------------------+---------+--------+ | 2014-01-01 10:01:00 | Car 1 | A | | 2014-01-01 10:01:00 | Car 1 | B | | 2014-01-01 10:01:00 | Car 1 | B | | 2014-01-01 10:03:00 | Car 1 | C | | 2014-01-01 10:03:00 | Car 1 | C | | 2014-01-01 10:03:00 | Car 1 | D | | 2014-01-01 10:03:00 | Car 1 | E | | 2014-01-01 10:03:00 | Car 1 | F | | 2014-01-01 10:05:00 | Car 1 | A | | 2014-01-01 10:05:00 | Car 1 | B | | 2014-01-01 10:05:00 | Car 1 | C | | 2014-01-01 10:05:00 | Car 1 | D | | 2014-01-01 10:05:00 | Car 1 | E | +---------------------+---------+--------+
当前结果:
+-----------------------------+-------+ | Unique Combo | Count | +-----------------------------+-------+ | 2014-01-01 10:01:00 Car 1 A | 1 | | 2014-01-01 10:01:00 Car 1 B | 2 | | 2014-01-01 10:03:00 Car 1 C | 2 | | 2014-01-01 10:03:00 Car 1 D | 1 | | 2014-01-01 10:03:00 Car 1 E | 1 | | 2014-01-01 10:03:00 Car 1 F | 1 | | 2014-01-01 10:05:00 Car 1 A | 1 | | 2014-01-01 10:05:00 Car 1 B | 1 | | 2014-01-01 10:05:00 Car 1 C | 1 | | 2014-01-01 10:05:00 Car 1 D | 1 | | 2014-01-01 10:05:00 Car 1 E | 1 | +-----------------------------+-------+
期望的结果:
+---------------------+---------+--------------------------------------------+ | Date Time | Vehicle | Unique Driver Count For Vehicle @ DateTime | +---------------------+---------+--------------------------------------------+ | 2014-01-01 10:01:00 | Car 1 | 2 | | 2014-01-01 10:03:00 | Car 1 | 4 | | 2014-01-01 10:05:00 | Car 1 | 5 | +---------------------+---------+--------------------------------------------+
答案 0 :(得分:0)
试试这个......
SELECT m.CurrentDateTime AS ' Date Time',v.VehicleName ,COUNT(m.Driver) AS 'Unique Driver Count For Vehicle @ DateTime '
FROM
Vehicles v
INNER JOIN MainData m ON l.VehicleID = m.VehicleID
WHERE
v.VehicleName = 'Car 1'
GROUP BY
m.CurrentDateTime
, v.VehicleName
ORDER BY CurrentDateTime
答案 1 :(得分:0)
我不完全确定您正在使用的SQL风格的确切语法,但我认为您希望对名称和日期进行分组,然后计算驱动程序。
SELECT
m.CurrentDateTime, v.VehicleName, count(distinct m.Driver)
FROM
Vehicles AS v INNER JOIN
MainData AS m
ON l.VehicleID = m.VehicleID
WHERE
v.VehicleName = 'Car 1'
GROUP BY
m.CurrentDateTime
, v.VehicleName
ORDER BY
m.CurrentDateTime
, v.VehicleName