sql - 分解整数范围以加入 SQL

标签 sql sql-server-2008 tsql join

我有一个表在一个字段中存储一系列整数,有点像打印范围,(例如“1-2,4-7,9-11”)。该字段也可以包含单个数字。

我的目标是将此表连接到具有离散值而不是范围的第二个表。

所以如果表一包含

1-2,5
9-15
7

表二包含
1
2
3
4
5
6
7
8
9
10

加入的结果将是
1-2,5   1
1-2,5   2
1-2,5   5
7       7
9-15    9
9-15    10

在 SQL Server 2008 R2 中工作。

最佳答案

使用 string split function of your choice 分隔逗号。找出最小值/最大值并使用它们之间的连接。

SQL Fiddle

MS SQL Server 2012 架构设置 :

create table T1(Col1 varchar(10))
create table T2(Col2 int)

insert into T1 values
('1-2,5'),
('9-15'),
('7')

insert into T2 values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)

查询 1 :
select T1.Col1,
       T2.Col2
from T2
  inner join (
              select T1.Col1,
                     cast(left(S.Item, charindex('-', S.Item+'-')-1) as int) MinValue,
                     cast(stuff(S.Item, 1, charindex('-', S.Item), '') as int) MaxValue
              from T1
                cross apply dbo.Split(T1.Col1, ',') as S
             ) as T1
    on T2.Col2 between T1.MinValue and T1.MaxValue

Results :
|  COL1 | COL2 |
----------------
| 1-2,5 |    1 |
| 1-2,5 |    2 |
| 1-2,5 |    5 |
|  9-15 |    9 |
|  9-15 |   10 |
|     7 |    7 |

关于sql - 分解整数范围以加入 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16618884/

相关文章:

asp.net - 创建数据库触发器到Sql DB

sql-server - 为什么我无法在 SQL Server 上查询 OFFSET/FETCH 查询?

sql-server - 在非常大的表中使用 CTE 与 WHILE 循环的 SQL 查询性能

sql-server - 给定日期范围内此查询的最快方法(最佳策略是什么)

sql-server - T-SQL : Ensure expression evaluation order in WHERE statement

mysql - 如何在 SQL 中查找并获取列值的差异

php - 使用POST方法将表单中的数据插入mysql

sql - Joomla:如何使用 LIKE 条件加载 JTable 元素

SQL Server : select distinct mon-yyyy format output sorty by descending order

sql-server-2008 - 如何解决错误 17836,严重性 : 20, 状态 : 14?