2017-10-06 72 views
3

我有個與客戶標識符PK和他的到期時間的表:在SQL中使用不同長度的創建序列

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

的[重複行×N時代根據可能的複製到列值](https://stackoverflow.com/questions/33327837/repeat-rows-n-times-according-to-column-value) – HABO

回答

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

1

你可以試着加入當前表的順序表,生成成熟的範圍你想要查詢。

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); 

演示在這裏:

Rextester

0

你可以試試下面的。 在下面的示例中創建了兩個臨時表來表示您的表。 您需要用表名替換它們,並放下前三行。

declare @Customer table (Customer int, Maturity int) 
declare @NewTable table (Customer int, Maturity int) 
insert @Customer select 1, 80 

declare @x int = 0 
declare @iterations table (x int) 
while @x <= (select max(Maturity) from @Customer) 
begin 
    set @x += 1 
    insert @iterations select @x 
end 

insert @NewTable 
select c.Customer, i.x from @Customer c left join @iterations i on i.x <= c.Maturity 

select * from @NewTable 
1

一種方法是使用遞歸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) 
0

遲到的回答,但另一種選擇是與CROSS音樂會的ad-hoc理貨表應用

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 
+0

我最喜歡你的答案,因爲你的r使用簡單的數字表如果號碼錶是永久的,那麼查詢就更簡單了。 – KumarHarsh

+0

@KumarHarsh實際上任何適當大小的表都可以。 spt_values有2,500條記錄。如果您需要更多,可以使用master..spt_values n1,master..spt_values n2,其中最多有6,365,529條記錄 –