SQLite最新和第二行之间的区别

时间:2016-04-12 20:09:37

标签: 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,  '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会返回最新值和第二个最新值之间的差异。

鉴于上表,我期待以下输出:

event_type  value
  2          -5
  3           4

据我所知SQL Sever/Oracle,可以使用row_number() over (partition by)来实现。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以随时模拟ROW_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;

SqlFiddleDemo

输出:

╔═══════════════╦═══════╗
║ event_type    ║ value ║
╠═══════════════╬═══════╣
║            2  ║    -5 ║
║            3  ║     4 ║
╚═══════════════╩═══════╝

time/events/value之类的标识符是某些SQL方言中的缩写词。