我写了一个应用程序,其中记录了许多车辆的使用情况,如截图所示。
我想生成个人使用之间的间隙(以英里为单位)的报告,因为除了应用程序中记录的旅行之外,不应使用车辆。
当前记录为里程表 - 前一记录结束里程表产生大于0的数字 - 对于该特定车辆时会出现间隙。看到不同的彩色圆圈。我怎样才能用sql实现这个目的?我使用的是oracle(11g),但我想sql会是类似的。谢谢。
示例输出:
Vehicle V06
Invoice Date Dest Gap
123 1/2/14 York 14.0
122 1/1/14 Pburg 0.0
Vehicle V05
Invoice Date Dest Gap
121 1/3/14 Mill 0.0
*我意识到我应该使用包含差距的测试数据,尽管这些在实践中应该是罕见的。在这种情况下,
Invoice 67189 would have End Od of 92590 resulting in a GAP of 3.0 miles for 67190
答案 0 :(得分:2)
只需使用lag()
:
select vu.*
from (select vu.*,
lag(endod) over (partition by vehicle order by date) as prev_endod
from vehicleusage vu
) vu
where begod <> prev_endod;
请注意,NULL
值的比较失败,因此首次录制车辆时没有问题。
答案 1 :(得分:0)
SELECT
D1.invoiceNo,
D1.vehicalId,
CASE WHEN D1.odBeg > D0.odEnd THEN 'MISSING MILES' ELSE 'EXTRA MILES' END AS Notes
FROM
(SELECT vehicalId,invoiceNo, RANK() OVER(PARTITION BY vehicalId ORDER BY dateUsed) AS KEY_CUR, odBeg,odEnd FROM @DATA) AS D0
INNER JOIN
(SELECT vehicalId,invoiceNo, RANK() OVER(PARTITION BY vehicalId ORDER BY dateUsed) - 1 AS KEY_LAST, odBeg,odEnd FROM @DATA) AS D1
ON D0.vehicalId = D1.vehicalId AND D0.KEY_CUR = D1.KEY_LAST
WHERE
D1.odBeg <> D0.odEnd