我有一张表格,其中客户标识符为PK,他的成熟时间为几个月:
Customer | Maturity
---------+-----------
1 80
2 60
3 52
4 105
我想创建一个具有客户标识符的表,成熟度将定义为数字序列,增量为+ 1:
Customer | Maturity
---------+------------
1 1
1 2
1 ....
1 80
2 1
2 2
2 ...
2 60
我不知道是否应该使用序列或交叉连接或如何解决此问题。
答案 0 :(得分:2)
您可以尝试将当前表连接到序列表以生成所需的成熟度范围。
WITH cte AS (
SELECT 1 AS seq
UNION ALL
SELECT seq + 1
FROM cte
WHERE seq < 500
)
SELECT
t1.Customer,
t2.seq AS Maturity
FROM yourTable t1
INNER JOIN cte t2
ON t2.seq <= t1.Maturity
ORDER BY
t1.Customer,
t2.seq
OPTION (MAXRECURSION 0);
在这里演示:
答案 1 :(得分:2)
一种方法是使用递归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)
答案 2 :(得分:1)
您可以尝试查询,如下所示
create table t (Customer int, Maturity int)
insert into t values
(1,80)
,(2,60)
,(3,52)
,(4,105);
select Customer, r from
t cross join
(select top (select max(maturity) from t)
row_number() over( order by (select NULL)) r
from sys.objects s1 cross join sys.objects s2) k
where r<=Maturity
order by Customer asc,r asc
的 see live demo 强>
答案 3 :(得分:0)
您可以尝试以下方法。 在下面的示例中创建了两个临时表来表示您的表。 您需要用表名替换它们并删除前三行。
base commit
答案 4 :(得分:0)
延迟回答,但另一个选项是与CROSS APPLY一致的临时计数表
示例强>
Select A.customer
,Maturity = B.N
From YourTable A
Cross Apply (
Select Top (A.Maturity) N=Row_Number() Over (Order By (Select NULL))
From master..spt_values n1
) B