如何将一行数据拆分为多行

时间:2017-10-09 11:41:23

标签: sql sql-server

我需要在表A中插入以下数据,并在表B中的多行中分配插入日期的触发器取决于表A中的数据

例如  表A具有以下数据:

Name    Start_Date      Totals  No_Payment    Diff_Date
Dave    1/10/17          10000        5           7

要分为表A进行5行的数据取决于No_Payment列,并根据Diff_Date列将7天添加到Start_Date。

谢谢

2 个答案:

答案 0 :(得分:0)

不确定您的要求,请重新解释。

declare @t table(Name varchar(50),  Start_Date date,Totals int, No_Payment int,Diff_Date int)
insert into @t values ('Dave','1/10/17',  10000 , 5, 7)
create table #num(num int)
insert into #num
select ROW_NUMBER()over(order by number) from master..spt_values

--select * from #num
SELECT *
    ,NewStartDate
    ,DATEADD(day, t.Diff_Date, NewStartDate) RequireStartDate
FROM @t t
CROSS APPLY (
    SELECT DATEADD(day, num, t.Start_Date) NewStartDate
    FROM #num
    WHERE num <= t.No_Payment
    ) c


drop table #num

答案 1 :(得分:0)

这是最简单的解决方案。

declare @t table (Name varchar(10), Start_Date datetime,Totals int,No_Payment int,Diff_Date int)
insert @t 
values ('Dave','1/10/17',10000,5,7),
       ('JOHN','2/10/17',10001,2,5),
       ('Fotos','3/10/17',10002,3,4),
       ('Manchi','7/10/17',10003,4,6)

select * from @t;

--Insert into <YOUR TABLE>
select t.Name
       , DATEADD(day,t.Diff_Date, t.Start_Date) as Start_Date
       ,t.Totals
       ,t.No_Payment
       ,t.Diff_Date
from   @t t
join   master..spt_values n
       on n.type = 'P'
       and n.number < convert(int,No_Payment,1)

它在SQLServer-2014中运行。

相关问题