查询在SQLite中不起作用

时间:2018-07-20 19:37:20

标签: sqlite subquery

为什么这在SQLite中不起作用,但在MySQL中起作用? 如果您能帮助我,那就太好了!

其他问题:我可以用联接替换子选择吗?

SELECT h1.drivers.name, SUM((
    SELECT kilometers FROM history AS h2
    WHERE h2.timestamp >= h1.timestamp
    AND h1.id != h2.id
    GROUP BY h2.timestamp HAVING MIN(h2.timestamp) LIMIT 1
    ) - h1.kilometers) AS driven_kilometers
FROM history AS h1
INNER JOIN drivers ON drivers.id = h1.driver_id
GROUP BY h1.driver_id

为澄清我的问题:

╔════╦═════════╦═════════════════════╦═══════════════╗
║ id ║driver_id║      timestamp      ║ kilometers    ║
╠════╬═════════╬═════════════════════╬═══════════════╣
║  1 ║    1    ║ 2018-07-01 12:00:04 ║             0 ║
║  2 ║    2    ║ 2018-07-01 16:05:12 ║           120 ║
║  3 ║    1    ║ 2018-07-06 11:13:59 ║           220 ║
║  4 ║    2    ║ 2018-07-09 09:17:19 ║           250 ║
║  5 ║    1    ║ 2018-07-12 10:02:00 ║           300 ║
║  6 ║    2    ║ 2018-07-16 07:11:21 ║           320 ║
╚════╩═════════╩═════════════════════╩═══════════════╝

我想计算行驶的公里数。 司机开始开车时会添加一个数据集,以便插入其他人开车的公里数。

示例:驾驶员2的公里数 我要计算:220-120 + 300-250 = 150

驾驶员1的公里 我要计算:120-0 + 250-220 + 320-300 = 170

1 个答案:

答案 0 :(得分:0)

在子查询中,分组没有意义,因为时间戳始终是唯一的。

要从具有下一个最大时间戳的行中获取值,只需将ORDER BY与LIMIT一起使用:

SELECT drivers.name,
       SUM((SELECT kilometers
            FROM history AS h2
            WHERE h2.timestamp > h1.timestamp
            ORDER BY h2.timestamp 
            LIMIT 1
           ) - h1.kilometers
          ) AS driven_kilometers
FROM history AS h1
INNER JOIN drivers ON drivers.id = h1.driver_id
GROUP BY h1.driver_id;