假设我们有一个这样的表:
*Assembly, name=Assembly
**
*Instance, name=vessel-1, part=vessel_bot
*Node
1, 24.8572464, 213.8125, 53.1415176
2, 41.4983292, 213.8125, 41.4983292
3, 44.4593391, 213.8125, 44.4593391
4, 28.0079861, 213.8125, 56.2922592
5, 24.8572464, 233.8125, 53.1415176
6, 28.0079861, 233.8125, 56.2922592
7, 48.2778168, 233.8125, 61.0057411
8, 46.156498, 233.8125, 61.0057411
9, 53.5811195, 223.3125, 53.5811195
10, 54.641777, 224.8125, 54.641777
11, 49.6920319, 233.8125, 62.4199524
12, 56.0559921, 224.8125, 56.0559921
13, 50.7526894, 233.8125, 61.3592911
14, 56.0559921, 226.3125, 56.0559921
15, 41.4983292, 226.3125, 41.4983292
16, 35.8528366, 233.8125, 46.4594383
17, 37.5893517, 233.8125, 52.4385948
18, 45.8735542, 223.3125, 45.8735542
19, 44.4593391, 221.3125, 44.4593391
20, 35.0599136, 233.8125, 52.1926079
21, 34.0794373, 233.8125, 44.686039
22, 31.5089321, 233.8125, 44.4683838
23, 38.5373192, 243.3125, 38.5373192
我需要做的是选择所有行,当作为序列查看时,结果中一行与下一行之间的最小差异至少为3.所需的结果应为:
id | num
---+----
1 | 1
2 | 3
3 | 5
4 | 6
5 | 7
6 | 8
这在命令式语言中是微不足道的:
id | num
---+----
1 | 1
3 | 5
6 | 8
但是我很难在纯SQL中找到解决方案(我正在使用SQLite,顺便说一句)。
我找到了一种看起来像这样的方式:
result = [table[0]]
for row in table:
if row['num'] >= result[-1]['num'] + 3:
result.append(row)
但这仅适用于特定版本的SQLite,后来的版本给出了错误,即递归查询中不允许使用聚合函数(在这种情况下为“min”)。
我认为可行的是:
WITH RECURSIVE
seq(t) as (
SELECT 1
UNION
SELECT min(num) FROM table, seq WHERE num >= t + 3 AND num < 10
)
SELECT t FROM seq;
但在这种情况下,WITH RECURSIVE
seq(t) as (
SELECT 1
UNION ALL
SELECT num FROM table, seq WHERE num >= t + 3 LIMIT 1
)
SELECT t FROM seq;
将应用于整个子查询,而不仅仅是第二个LIMIT 1
,因此最后SELECT
只有一行。
可以这样做吗?