我有一个表在一个字段中存储一系列整数,有点像打印范围,(例如“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/