Sql 选择连续的数据对

Sql 选择连续的数据对,sql,database,sqlite,Sql,Database,Sqlite,我有一个树木清单测量数据库,其模式如下: sqlite> .schema mmt CREATE TABLE mmt (mmtid INTEGER PRIMARY KEY, plot TEXT, mmtDate TEXT, treeno NUMERIC, fork TEXT, diameter NUMERIC, height NUMERIC, cwn NUMERIC, form NUMERIC, thin TEXT, comments TEXT, row NUMERIC, heightfla

我有一个树木清单测量数据库,其模式如下:

sqlite> .schema mmt
CREATE TABLE mmt (mmtid INTEGER PRIMARY KEY, plot TEXT, mmtDate TEXT, treeno NUMERIC, fork TEXT, diameter NUMERIC, height NUMERIC, cwn NUMERIC, form NUMERIC, thin TEXT, comments TEXT, row NUMERIC, heightflag TEXT);
;
树木属性(直径和高度)每隔几年测量一次。下面是对应于图abc101中树1的数据片段。这棵树在2000年、2001年、2003年、2006年和2009年进行了测量。fork字段表示在一棵树上进行了多个度量,但这不适用于以下数据:

sqlite> select * from mmt where plot = "abc101" and treeno = 1 ;
mmtid|plot|mmtDate|treeno|fork|diameter|height|cwn|form|thin|comments|row|heightflag
45488|abc101|2000-06-23 00:00:00|1|NULL|14.7||2|2|||1|
45497|abc101|2001-07-20 00:00:00|1|NULL|15.6||2|2|||1|
53683|abc101|2003-09-03 00:00:00|1|NULL|17.3||1|2|||1|
62435|abc101|2006-08-22 00:00:00|1|NULL|20.4|19.25|1|1|||1|H
71314|abc101|2009-01-14 00:00:00|1|NULL|24.1|20.4|1|1|||1|H
我希望对数据进行结构化,以便查看连续的测量对,例如:

plot|mmt1date|treeno|fork|dbh1|mmt2date|dbh2
abc101|2000-06-23 00:00:00|1|NULL|14.7|2001-07-20 00:00:00|15.6
abc101|2001-07-20 00:00:00|1|NULL|15.6|2003-09-03 00:00:00|17.3


我相信这是一个相当微不足道的问题。不幸的是,我的sql不是它可能是什么,我还没有找到一个工作的解决方案,在这个阶段。请问有人能就合适的方法提出建议吗

您需要一个自联接。不幸的是,sqlite不支持一些涉及窗口函数的聪明方法

SELECT *
FROM mmt m1 JOIN mmt m2
ON m1.plot = m2.plot /* whatever else identifies the tree */
AND m2.mmtDate = 
  (SELECT MIN(mmtDate) FROM mmt m3 
   WHERE m3.plot = m1.plot AND m3.mmtDate > m1.mmtDate);
注意,在子查询中使用
orderbym3.mmt日期限制1
可以获得更好的性能

如果这是一个大表,我建议为有条目的年份创建一个特殊的查找表,按升序键入,增量为1

sequence_number   year
1                 2000
2                 2001
3                 2003 /* etc */
等等

然后试试看

SELECT *
FROM mmt m1 JOIN mmt m2
ON m1.plot = m2.plot /* whatever else identifies the tree */
  JOIN year_list y1 ON year(m1.mmtDate)=y1.year
  JOIN year_list y2 ON year(m2.mmtDate)=y2.year
    AND y1.sequence_number = y2.sequence_number-1;