2015-04-30 66 views
0

我已經得到了接下來的情況(SQL SERVER 2012):SQL生成日期範圍內每天記錄

這是我的源表(日期是DD-MM-YYYY):

id|startDate |updateDate |percentage 
--|------------|------------|---------- 
01| 01-01-2015| 03-01-2015| 45 
01| 01-01-2015| 05-01-2015| 80 
01| 01-01-2015| 06-01-2015| 100 

我想與如下因素表結束:

id|date  |percentage 
--|------------|---------- 
01| 01-01-2015| 0 
01| 02-01-2015| 0 
01| 03-01-2015| 45 
01| 04-01-2015| 45 
01| 05-01-2015| 80 
01| 06-01-2015| 100 

我的計劃是做一個日期表的連接,但我主要關注的是如何產生的記錄,其中的比例是0,因爲源只有一個startdate和第一個更新。

所以當我看到它時,首先我需要在startDate和第一個updateDate之間做一個datediff,從當前的updateDate和之前的updateDate之間的一個更新。那是我關心的地方,我該如何做這項工作?

在此先感謝!

PS。 datetable僅僅是一個簡單的表與裏的每個日期

id|date  |month |etc... 
--|------------|------|------- 
01| 01-01-2015| 1 | 
01| 02-01-2015| 1 | 
01| 03-01-2015| 1 | 
01| 04-01-2015| 1 | 
01| 05-01-2015| 1 | 
01| 06-01-2015| 1 | 
etc... 
+0

您能否提供一些關於您的日期表的更多信息,您將加入? – FutbolFan

+1

請編輯你的問題,包括你已經嘗試過的內容 –

+0

嘗試加入日期表,但我堅持如何從私密記錄獲取updateDate – NCS

回答

1

一種方法(使用遞歸CTE):

; with cte as 
(select '01' id, cast('2015-01-01' as datetime) [date], 0 percentage 
union all 
select c.id, 
     dateadd(DAY,1,c.[date]) [date], 
     coalesce((select s.percentage 
        from SourceTable s 
        where c.id = s.id and dateadd(DAY,1,c.[date]) = s.updatedate), 
       c.percentage) percentage 
from cte c 
where c.[date] < '2015-01-06') 
select * from cte 

SQLFiddle here

+1

我已經玩了一點點,使它更具動感。 [檢查它。](http://sqlfiddle.com/#!6/f549e/7) –

+0

@ZoharPeled,你有提示改變它,使其與更多的ID的工作? – NCS

+0

@NCS,目前不在,對不起。我試過但沒有成功。或許Mark會找到方法 –

0

首先將您的日期助手錶與updateDate上的源表連接起來。 然後,我已經將一個子查詢關聯起來,以獲得比我們當前加入的日期更少的任何日期的最大百分比。

With tblDates AS (
     select * 
     from Dates d 
     left join Table1 t on CAST(d.date as date) = t.updateDate 
     ) 
    select d.id, 
      d.[date], 
      (select ISNULL(max(percentage), 0) 
      from tblDates d1 
      where d1.[date] < d.[date]) as percentage 
    from tblDates d 
相關問題