最新行和第二最新行之间的SQLite差异
我有这样的桌子:最新行和第二最新行之间的SQLite差异,sql,sqlite,Sql,Sqlite,我有这样的桌子: create table events( event_type integer not null, value integer not null, time timestamp not null, unique (event_type ,time) ); insert into events values (2, 5, '2015-05-09 12:42:00'), (4, -42, '2015-05-09 13:19:57'), (2, 2, '201
create table events(
event_type integer not null,
value integer not null,
time timestamp not null,
unique (event_type ,time)
);
insert into events values
(2, 5, '2015-05-09 12:42:00'),
(4, -42, '2015-05-09 13:19:57'),
(2, 2, '2015-05-09 14:48:39'),
(2, 7, '2015-05-09 13:54:39'),
(3, 16, '2015-05-09 13:19:57'),
(3, 20, '2015-05-09 15:01:09')
我希望看到一个查询,对于已注册多次的每个事件类型
,返回最新值和第二个最新值之间的差值
鉴于上表,我期望得到以下结果:
event_type value
2 -5
3 4
正如我在
SQL服务器/Oracle
中所知道的,这可以通过使用row\u number()覆盖(分区)
来实现。您可以始终模拟row\u number
:
WITH cte AS
(
SELECT *,
(SELECT COUNT(*) + 1
FROM "events" e1
WHERE e1.event_type = e.event_type
AND e1.time > e.time) AS rn
FROM "events" e
)
SELECT c.event_type, c."value" - c2."value" AS "value"
FROM cte c
JOIN cte c2
ON c.event_type = c2.event_type
AND c.rn = 1 AND c2.rn = 2
ORDER BY event_type, time;
输出:
╔═══════════════╦═══════╗
║ event_type ║ value ║
╠═══════════════╬═══════╣
║ 2 ║ -5 ║
║ 3 ║ 4 ║
╚═══════════════╩═══════╝
像
time/events/value
这样的标识符在某些SQL方言中是重新排序的单词