2
SELECT
    MAX(timestamp) as end,
    MIN(timestamp) as start, 
    (MAX(odometerKM) - MIN(odometerKM)) as distanceTravelled,
    ( SELECT COUNT(*) FROM EventData WHERE speedKPH = 0 AND timestamp >= ? AND timestamp <= ? AND  deviceID = ?)  as stopsDuration,
    ( SELECT COUNT(*) FROM EventData WHERE speedKPH != 0 AND timestamp >= ? AND timestamp <= ? AND  deviceID = ? )  as tripDuration,
    (MAX(odometerKM) - MIN(odometerKM)) / ( SELECT fuelEconomy FROM Device WHERE deviceID = ?) as fuelConsumption
FROM EventData
WHERE deviceID = ? AND timestamp >= ? AND timestamp <= ?

相当混乱,但我创建了这个查询来查找一组行的摘要。最小和最大时间戳很简单,但要找到速度为零而不是零的行数,我做了一个丑陋的 hack。我确定有更好的方法来做到这一点?

更新:“?” 指代被 CodeIgniter 的一个不成熟的查询生成器所取代。遗憾的是,它还不支持命名参数。

4

2 回答 2

0

您应该包括 DeviceID,所以这是有道理的。尝试这个:

SELECT
DeviceID,
MAX(timestamp) as end,
MIN(timestamp) as start, 
(MAX(odometerKM) - MIN(odometerKM)) as distanceTravelled,
SUM (
  case speedKPH 
    when  0  then 1
    else 0
  end)  as stopsDuration,

SUM (
  case speedKPH 
    when  0  then 0
    else 1
  end)  as tripDuration,

(MAX(odometerKM) - MIN(odometerKM)) / Device.fuelEconomy  as fuelConsumption

FROM EventData
Join Device ON Device.deviceID = EventData.deviceID 

WHERE deviceID = ? AND timestamp >= ? AND timestamp <= ?

GROUP BY  DeviceID
于 2013-06-21T15:10:37.720 回答
0

我会摆脱列子查询。你可以像这样计算stopsDurationtripDuration我暂时省略fuelConsumption):

SELECT
  MAX(timestamp) as end, MIN(timestamp) as start, 
  MAX(odometerKM) - MIN(odometerKM) as distanceTravelled,
  COUNT(speedKPH = 0 AND timestamp >= ? AND timestamp <= ?) as stopsDuration
  COUNT(speedKPH != 0 AND timestamp >= ? AND timestamp <= ?) as tripDuration
FROM EventData WHERE deviceID = ? AND timestamp >= ? AND timestamp <= ?

您可以通过交叉连接到表的单个适用行来摆脱fuelComparison子查询Device

SELECT
  (MAX(odometerKM) - MIN(odometerKM)) / dv.fuelEconomy as fuelConsumption
FROM
  EventData,
  (SELECT Device.fuelEconomy FROM Device WHERE DeviceId = ?) dv
WHERE deviceID = ? AND timestamp >= ? AND timestamp <= ?

把它们放在一起,你就得到了,它(至少在纸上)应该更快:

SELECT
  MAX(timestamp) as end, MIN(timestamp) as start, 
  MAX(odometerKM) - MIN(odometerKM) as distanceTravelled,
  COUNT(speedKPH = 0 AND timestamp >= ? AND timestamp <= ?) as stopsDuration
  COUNT(speedKPH != 0 AND timestamp >= ? AND timestamp <= ?) as tripDuration,
  (MAX(odometerKM) - MIN(odometerKM)) / dv.fuelEconomy as fuelConsumption
FROM
  EventData,
  (SELECT Device.fuelEconomy FROM Device WHERE DeviceId = ?) dv
WHERE deviceID = ? AND timestamp >= ? AND timestamp <= ?
于 2013-06-21T15:10:42.020 回答