我有一个包含指标和值列表的表
OrigTable
Index Value
1 10
2 11
3 16
4 18
5 14
6 11
7 10
8 12
9 20
10 17
我需要使用另外两个表来分隔值。
Table1
将包含来自OrigTable
的行Value
< = 15,
Table2
将包含> 15,但在任一方向上都包含一个点,这样如果index n 对应的值大于15,它将包含在表2中,但是所以会指示 n-1 和 n + 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确定一种方法。这是不可能的,还是我错过了一些可以使这个变得可行的命令?
编辑:表1中将包括15;我忘了添加'或等于'。通过“任意一个方向上的一个点”,我的意思是如果索引 n 对应于大于15的值,它将包含在表2中,但是也会指示 n -1 和 n + 1
答案 0 :(得分: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
答案 1 :(得分:1)
你只需要一个点,它可能不是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
)