Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating sequence in SQL with different length

I have a table with the customer identifier as PK and his time to maturity in months:

Customer |  Maturity
---------+-----------
1             80
2             60
3             52
4             105

I want to create a table which will have customer identifier and the maturity will be defined as sequence of number with the increment + 1:

Customer |  Maturity
---------+------------
1             1
1             2
1            ....
1             80
2             1
2             2
2            ...
2             60

I don't know whether I should use a sequence or the cross join or how to solve this problem.

like image 841
Ivan Klimcak Avatar asked Sep 28 '26 01:09

Ivan Klimcak


1 Answers

one way is to use recursive CTE.

; with cte as
(
    select  Customer, M = 1, Maturity
    from    yourtable
    union all
    select  Customer, M = M + 1, Maturity
    from    yourtable
    where   M < Maturity
)
select  *
from    cte
option (MAXRECURSION  0)
like image 195
Squirrel Avatar answered Sep 29 '26 16:09

Squirrel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!