0

假设我有一个包含以下列(开始、结束、间隔)的表

有什么方法可以获取 Start 和 End 之间的所有值,每个值都在一行上?请注意,(开始,结束,间隔)表中的行数将超过一行,但它们不应重叠。

如果可能没有循环/游标/临时表/变量表。

样本数据

开始结束间隔
1 3 1
9 12 1
16 20 2

期望的结果:

结果
1
2
3
9
10
11
12
16
18
20
4

3 回答 3

4

这是递归公用表表达式的一个很好的用例:

;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

sql fiddle demo

于 2013-10-17T13:56:15.837 回答
2

你可以这样做

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的持久数字表。tallyn

输出:

| 结果 |
|--------|
| 1 |
| 2 |
| 3 |
| 9 |
| 10 |
| 11 |
| 12 |
| 16 |
| 18 |
| 20 |

这是SQLFiddle演示

于 2013-10-17T13:38:40.493 回答
1

我知道你已经接受了答案,我认为这也是正确的。

小提琴演示 1 ;

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。

小提琴演示 2

;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
于 2013-10-17T13:51:44.477 回答