根据列克隆行

时间:2015-12-09 08:11:51

标签: sql sql-server

我的数据如下所示:

ID  Duration  Start Date          End Date
------------------------------------------------------
10  2         2013-09-03 05:00:00 2013-09-03 05:02:00

我需要输出如下:

10  2        2013-09-03 05:00:00 2013-09-03 05:01:00  1  
10  2        2013-09-03 05:01:00 2013-09-03 05:02:00  2

根据列Duration,如果值为2,我需要重复两次行。

如果我们在“Start DateEnd Date时间的输出中看到,则应相应更改。

并且Row count作为在这种情况下重复的数字行的附加列,如上所示1/2将有很大帮助。

如果持续时间为0和1,则不执行任何操作,仅在持续时间> 1然后重复行。 最后是数字行序列1,2,3的附加列,用于显示重复的行数。

2 个答案:

答案 0 :(得分:1)

尝试下面的sql,我添加了一些评论,我认为这似乎是必要的。

declare @table  table(Id integer not null, Duration int not null, StartDate datetime, EndDate datetime)

insert into @table values (10,2, '2013-09-03 05:00:00', '2013-09-03 05:02:00')
insert into @table values (11,3, '2013-09-04 05:00:00', '2013-09-04 05:03:00')



;WITH 
 numbers AS (
--this is the number series generator 
--(limited to 1000, you can change that to whatever you need
-- max possible duration in your case).
    SELECT 1 AS num
    UNION ALL
    SELECT num+1 FROM numbers WHERE num+1<=100
)
SELECT t.Id
    , t.Duration
    , StartDate = DATEADD(MINUTE, IsNull(Num,1) - 1, t.StartDate)
    , EndDate = DATEADD(MINUTE, IsNull(Num,1), t.StartDate)
    , N.num
FROM @table t
LEFT JOIN numbers N
    ON t.Duration >= N.Num
-- join it with numbers generator for Duration times
ORDER BY t.Id
    , N.Num

答案 1 :(得分:0)

当持续时间= 0时,这种方法效果更好:

declare @table  table(Id integer not null, Duration int not null, StartDate datetime, EndDate datetime)

insert into @table values (10,2, '2013-09-03 05:00:00', '2013-09-03 05:02:00')
insert into @table values (11,3, '2013-09-04 05:00:00', '2013-09-04 05:03:00')
insert into @table values (12,0, '2013-09-04 05:00:00', '2013-09-04 05:03:00')
insert into @table values (13,1, '2013-09-04 05:00:00', '2013-09-04 05:03:00')
;WITH 
 numbers AS (
--this is the number series generator 
--(limited to 1000, you can change that to whatever you need
-- max possible duration in your case).
    SELECT 1 AS num
    UNION ALL
    SELECT num+1 FROM numbers WHERE num+1<=100
)
SELECT 
      Id
    , Duration
    , StartDate
    , EndDate 
    , num
FROM 
(SELECT 
      t.Id
    , t.Duration
    , StartDate = DATEADD(MINUTE, Num - 1, t.StartDate)
    , EndDate = DATEADD(MINUTE, Num, t.StartDate)
    , N.num
FROM @table t
INNER JOIN numbers N
    ON t.Duration >= N.Num ) A
-- join it with numbers generator for Duration times
UNION 
(SELECT 
      t.Id
    , t.Duration
    , StartDate-- = DATEADD(MINUTE, Num - 1, t.StartDate)
    , EndDate --= DATEADD(MINUTE, Num, t.StartDate)
    , 1 AS num
FROM @table t
WHERE Duration = 0)
ORDER BY Id,Num