首页 > 解决方案 > 基于sql中输入范围的数字范围拆分

问题描述

我有表(table1),数据为

SlNo NumberStart NumberEnd   Volume
1     101              110    10 
2     301              301     1

我的 jquery 输入是 Number of volume is requested as

Volume: 3

NumberStart          NumberEnd
  301                   301
  103                   103

当我过滤 table1 数据中的输入时,选择语句结果应拆分如下

 NumberStart     NumberEnd      isSplitted    Volume
        301              301            Yes       1
        101              102            Yes       2
        103              103            Yes       1 
        104              110            No        7

所以我要求的第 3 卷被拆分了。

您能否请任何人分享上述的 SELECT 语句?

标签: sqlsql-server

解决方案


您试图实现的确切逻辑有点模糊。您似乎正在table1根据table2. 对于匹配的部分,is_splitted = 1.

以下返回您指定的结果:

select t1.NumberStart, t2.NumberEnd, 1 as is_splitted, t2.NumberEnd - t1.NumberStart as volume
from table1 t1  join
     table2 t2
     on t1.NumberStart = t2.NumberStart
union all
select t2.NumberStart + 1, t1.NumberEnd, 0 as is_splitted, t1.NumberEnd - t2.NumberEnd as volume
from table1 t1 join
     table2 t2
     on t1.NumberStart = t2.NumberStart
where t2.NumberEnd <> t1.NumberEnd;

是一个 db<>fiddle。


推荐阅读