SQL 重叠排序

SQL Sorting With Overlap

我有一个 table 包含一个索引和值列表

OrigTable

Index     Value
  1        10
  2        11
  3        16
  4        18
  5        14
  6        11
  7        10
  8        12
  9        20
 10        17

我需要使用另外两个 table 来分隔值。

Table1 将包含来自 OrigTable 的行,其中 Value 是 <=15,并且

Table2 将包含 >15,但也包含任一方向的一个点,因此如果索引 n 对应于大于 15 的值,它将包含在Table 2,但指数 n-1n+1

因此结果将

Table1:

Index    Value
  1        10
  2        11
  5        14
  6        11
  7        10
  8        12

Table2:

Index    Value
  2        11
  3        16
  4        18
  5        14
  8        12
  9        20
 10        17

我无法确定使用 SQL 执行此操作的方法。这是不可能的,还是我遗漏了一些使它可行的命令?

编辑:15 将包含在 Table 1 中;我忘了添加 'or equal to'。通过 'one point in either direction',我的意思是如果索引 n 对应于大于 15 的值,它将包含在 Table 2 中,但索引 n-1n+1

create table OrigTable
( 
theIndex int not null,
theValue int not null
);

insert into OrigTable (theIndex,theValue) values (1,10),(2,11),(3,16),(4,18),(5,14),(6,11),(7,10),(8,12),(9,20),(10,17);
-- select * from OrigTable;

create table table1
( 
theIndex int not null,
theValue int not null
);

create table table2
( 
theIndex int not null,
theValue int not null
);

insert into table1 (theIndex,theValue) select theIndex,theValue from OrigTable where theValue<=15;

insert into table2 (theIndex,theValue) select theIndex,theValue from OrigTable where theValue>15;

insert into table2 (theIndex,theValue) 
select a.theIndex,a.theValue 
from table2 b
join OrigTable a
on a.theIndex=b.theIndex-1
where a.theIndex not in (select theIndex from table2)

insert into table2 (theIndex,theValue) 
select a.theIndex,a.theValue 
from table2 b
join OrigTable a
on a.theIndex=b.theIndex+1
where a.theIndex not in (select theIndex from table2)



select * from table1 order by theIndex
select * from table2 order by theIndex

你只需要一个点,它可能不是15。所以,对于第一个查询:

select t.*
from table t
where t.value <= 15

第二个:

(select t.*
 from table t
 where t.value <= 15
 order by t.value desc
 limit 1
) union all
(select t.*
 from table t
 where t.value > 15
)