将包含开始日期和结束日期的1条记录转换为每天的多条记录

时间:2014-10-11 16:55:06

标签: sql sql-server tsql

我想知道一种有效的方法来记录开始日期和结束日期的事件记录,并基本上复制开始日期和结束日期之间每天的记录

因此,开始日期为2014-01-01,结束日期为2014-01-03的记录将成为3条记录,每天一条记录

如果有帮助,我有一个日期表。我使用的是SQL Server 2012

由于

5 个答案:

答案 0 :(得分:4)

由于您已有日期表,您可以使用日期表加入您的表格,以使所有日期与开始日期和结束日期具有相同的记录

 SELECT A.data,
    DT.startDate,
    DT.endDate
 FROM
 DateTable DT
 JOIN A
 ON A.StartDate >= DT.startDate
 And A.EndDate <= DT.endDate

答案 1 :(得分:3)

使用此查询

declare @startDate datetime = getdate()
declare @endDate datetime = dateadd(day,10,getdate())


;with days as 
(
    select
        @startDate as StartDate,
        @endDate as EndDate,
        @startDate as CurrentDate,
        0 as i
    union all
    select 
        d.StartDate,
        d.EndDate,
        dateadd(day,d.i + 1,@startDate) as CurrentDate,
        d.i + 1 as i
    from days d
    where dateadd(day,d.i + 1,@startDate) < d.EndDate
)
select
*
from days d

答案 2 :(得分:1)

试试这个

DECLARE @dt1 Datetime='2014-01-01'
DECLARE @dt2 Datetime='2014-01-03'
;WITH ctedaterange
     AS (SELECT [Dates]=@dt1
         UNION ALL
         SELECT [dates] + 1
         FROM   ctedaterange
         WHERE  [dates] + 1<= @dt2)
SELECT [dates]
FROM   ctedaterange
OPTION (maxrecursion 0)

答案 3 :(得分:0)

SELECT COl1,COL2, split.a.value('.', 'VARCHAR(100)') data 
FROM   (SELECT COl1,COL2, Cast ('<M>' 
                     + Replace(LEFT(Replicate(NAME+',', datediff(dd,startdate,endate),    Len(Replicate(NAME+',', datediff(dd,startdate,endate)))-1), ',''</M><M>') 
                 + '</M>' AS XML) AS Data 
    FROM   tablename) AS A 
   CROSS apply data.nodes ('/M') AS Split(a) 

答案 4 :(得分:0)

查询

DECLARE @StartDate DATE = '2014-01-01',
        @EndDate   DATE = '2014-01-03';

SELECT TOP (DATEDIFF(DAY, @StartDate, @EndDate) + 1)
      DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.number) - 1, @StartDate) AS Date_Range
FROM master..spt_values a
                   CROSS APPLY master..spt_values b;

结果

Date_Range
2014-01-01
2014-01-02
2014-01-03