SQL拆分范围到单个行

问题描述 投票:2回答:2

我有这样一张桌子:

JOBNO   STARTNO     ENDNO
123     1           5
456     6           7
789     8           10

我需要像这样的输出:

STARTNO    JOBNO
1          123
2          123
4          123
5          123
6          456
7          456
8          789
9          789
10         789
sql
2个回答
2
投票

你想要递归cte

with cte as (
     select jobno, startno, endno
     from table t
     union all
     select jobno, startno + 1, endno
     from cte c
     where startno < endno
)
select c.startno, c.jobno
from cte c
order by c.jobno, c.startno;

这假设您正在使用SQL Server运行,否则语法可能会有所不同。

如果option (maxrecursion 0)有更多的差距,请使用startno


0
投票

您没有指定DBMS,但对于Postgres,您可以使用generate_series()

select x.i as startno, j.jobno
from jobs j
  join generate_series(j.startno, j.endno) as x(i) on true;

在线示例:https://rextester.com/RZN4872

© www.soinside.com 2019 - 2024. All rights reserved.