之间的所有值,可以说我有以下几列 表(开始,结束,时间间隔)选择两个值
有没有什么办法让开始之间的所有值,与间隔结束每一个行? 注意在(Start,End,Interval)表格中会多出一行,但它们不应该重叠。
如果可能,不使用循环/游标/临时表/变量表。
的样本数据
Start End Interval 1 3 1 9 12 1 16 20 2
期望的结果:
Result 1 2 3 9 10 11 12 16 18 20
之间的所有值,可以说我有以下几列 表(开始,结束,时间间隔)选择两个值
有没有什么办法让开始之间的所有值,与间隔结束每一个行? 注意在(Start,End,Interval)表格中会多出一行,但它们不应该重叠。
如果可能,不使用循环/游标/临时表/变量表。
的样本数据
Start End Interval 1 3 1 9 12 1 16 20 2
期望的结果:
Result 1 2 3 9 10 11 12 16 18 20
这是一个伟大的使用情况递归公用表表达式:
;with cte as (
select [Start] as Result, [End], [Interval]
from Table1
union all
select Result + [Interval], [End], [Interval]
from cte
where Result + [Interval] <= [End]
)
select Result
from cte
order by Result
你可以像下面这样做
WITH tally AS (
SELECT 0 n
UNION ALL
SELECT n + 1 FROM tally WHERE n < 100 -- adjust 100 to a max possible value for (end - start)/interval
)
SELECT start + n * [interval] result
FROM Table1 t CROSS JOIN tally n
WHERE n.n <= (t.[end] - t.start)/t.[interval]
ORDER BY result
注:如果你做了很多这样的查询,你可能考虑替换递归CTE tally
带有n
列上的主键的持久数字表tally
。
输出:
| RESULT | |--------| | 1 | | 2 | | 3 | | 9 | | 10 | | 11 | | 12 | | 16 | | 18 | | 20 |
这里是SQLFiddle演示
我知道你已经接受了答案,我想这也是正确的。
select x.number
from master..spt_values x cross join table1 t
where x.type='p' and x.number between t.[start] and t.[end]
and x.number % t.[interval] = 0
结果:
| NUMBER |
|--------|
| 1 |
| 2 |
| 3 |
| 9 |
| 10 |
| 11 |
| 12 |
| 16 |
| 18 |
| 20 |
编辑:如果你想要去的数量没有限制尝试这种方法,并根据需要交叉连接更多的数字表。这个例子上升到9999
;WITH Digits AS (
select Digit
from (values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9))
AS t(Digit))
,Numbers AS (
select u.Digit + t.Digit*10 + h.Digit*100 + th.Digit*1000 as number
from Digits u
cross join Digits t
cross join Digits h
cross join Digits th
--Add more cross joins as required
)
Select number
From Numbers x cross join table1 t
where x.number between t.[start] and t.[end]
and x.number % t.[interval] = 0;
Order by number
不要淡漠d你的措辞,你可以重述一下这个问题吗? –
您能否提供示例输入数据和期望的输出? – jpw
更改了文字并添加了输入值和输出的示例。 – Peter