TSQL插入其他行

时间:2015-04-21 09:40:32

标签: tsql sql-server-2008-r2

为以下问题识别和插入行的最有效方法是什么?

这是我的示例数据

vId StartDate   EndDate     Distance
------------------------------------    
256 2015-03-04  2015-03-05  365
271 2015-03-04  2015-03-04  86
315 2015-03-05  2015-03-06  254
256 2015-03-07  2015-03-09  150
458 2015-03-10  2015-03-12  141
458 2015-03-15  2015-03-17  85
315 2015-03-15  2015-03-16  76

我想为vId之类的每个StartDate <> EndDate添加额外的行,而不仅仅是

315 2015-03-05  2015-03-06  254
256 2015-03-07  2015-03-09  150

我想展示以下内容

315 2015-03-05  2015-03-06  254
315 2015-03-06  2015-03-06  0

256 2015-03-07  2015-03-09  150
256 2015-03-08  2015-03-09  0
256 2015-03-09  2015-03-09  0

提前致谢。

1 个答案:

答案 0 :(得分:1)

只是一个简单的插入:

Insert Into Table(vId, StartDate, EndDate, Distance)
Select vId, DateAdd(dd, 1, StartDate), EndDate, 0
From TableName
Where StartDate <> EndDate

如果您只想选择但不插入则:

Select vId, StartDate, EndDate, Distance
From TableName

Union All

Select vId, DateAdd(dd, 1, StartDate), EndDate, 0
From TableName
Where StartDate <> EndDate

修改

这假设最多有100天的差异。如果间隔较长,则可以添加更多交叉连接以增加可能的值:

declare @t table(vId int, StartDate date, EndDate date, Distance int)

insert into @t values
(315, '2015-03-05',  '2015-03-06',  254),
(256, '2015-03-07',  '2015-03-09',  150)


;with cte as(select row_number() over(order by (select 1)) as rn
             from (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t1(n)
             cross join (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t2(n)
            )

select * from @t
union all
select t1.vId, ca.StartDate, t1.EndDate, 0 
from @t t1
cross apply(select dateadd(dd, c.rn, StartDate) as StartDate 
            from cte c 
            where dateadd(dd, c.rn, t1.StartDate) <= t1.EndDate) as ca
where t1.StartDate <> t1.EndDate
order by vId, StartDate

请参阅小提琴http://sqlfiddle.com/#!6/9eecb/4641