【问题标题】:SQL Sorting With Overlap重叠的 SQL 排序
【发布时间】:2015-08-24 11:54:49
【问题描述】:

我有一个包含指标和值列表的表格

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

Table2 将包含 >15,但在任一方向也包含一个点,因此如果索引 n 对应于大于 15 的值,它将包含在表 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 将包含在表 1 中;我忘了加上“或等于”。 “任一方向的一个点”是指如果索引 n 对应于 15 以上的值,它将包含在表 2 中,但索引 n-1n+1

【问题讨论】:

  • 为什么索引 2 在两个表中? also containing one point in either direction 到底是什么意思
  • 可怜的15岁呢,如果她还活着,她会去哪里
  • 您使用的是哪个 DBMS? sql server mysql

标签: sql sorting overlap


【解决方案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

【讨论】:

    【解决方案2】:

    你只需要一个点,它可能不是 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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      相关资源
      最近更新 更多