Pun*_*eet 4 sql sqlite greatest-n-per-group
我在SQLite中有一个表
/* Create a table called NAMES */
CREATE TABLE EVENTS(Id integer , Eventtype integer,value integer,Timestamp DATETIME);
/* Create few records in this table */
INSERT INTO EVENTS VALUES(1,2,1,'2009-01-01 10:00:00'); --ROW1
INSERT INTO EVENTS VALUES(1,2,2,'2007-01-01 10:00:00'); --ROW2
INSERT INTO EVENTS VALUES(2,2,3,'2008-01-01 10:00:00’); --ROW3
Run Code Online (Sandbox Code Playgroud)
查询所需要的是ROW1和ROW3.对于重复的ID和Eventtype组合,查询应采用最新的基于行的时间戳.ROW1和ROW2具有相同的eventtype和id但ROW1是最新的,因此应该选择它.
在SQLite 3.7.11或更高版本中,您可以使用GROUP BY和MAX()来选择要返回的组中的哪一行:
SELECT *, MAX(timestamp)
FROM events
GROUP BY id, eventtype
Run Code Online (Sandbox Code Playgroud)
在早期版本中,您必须使用子查询查找组中最大行的唯一ID(如您的回答).