检索并连接数周的历史日期

时间:2017-07-21 10:19:31

标签: sql-server date formatting type-conversion string-concatenation

我正在尝试复制一些旧的Excel模板,它们设置的方式并不理想,但我将它们用作练习。

在excel表中有一个如下所示的列:

|--Week and dates--|
|------------------|
|Week 291214_040115|
|Week 050115_110115|
|Week 120115_180115|
|...etc............|
|...etc............|
|...etc............|
|...etc............|
|Week 030717_090717|
|Week 100717_160717|

使用下面的代码我尝试重新创建上面的代码但是我遇到了几个问题。

Declare @sDate date,
        @eDate date;

Select  @sDate = '2015-01-01',
        @eDate = '2017-07-31';

;with cte as
(
select @sDate StartDate, 
DATEADD(wk, DATEDIFF(wk, 0, @sDate), 6) EndDate

union all

select dateadd(ww, 1, StartDate),
dateadd(ww, 1, EndDate)

from cte
where dateadd(ww, 1, StartDate)<=  @eDate
)

select concat(StartDate,'_',EndDate) as date

from cte
OPTION (MAXRECURSION 0)

它产生的输出是:

|------------Dates-------------|
|2015-01-01_Jan  4 2015 12:00AM|
|2015-01-08_Jan 11 2015 12:00AM|
|2015-01-15_Jan 18 2015 12:00AM|
|2015-01-22_Jan 25 2015 12:00AM|
|2015-01-29_Feb  1 2015 12:00AM|
|2015-02-05_Feb  8 2015 12:00AM|

我没有连接字符串&#34;周&#34;进入脚本,但基本上我如何让脚本看起来更像excel模板表,而不像我自己的版本。

1 个答案:

答案 0 :(得分:0)

您可以更改以下选项:

select concat('Week ',Format(StartDate, 'ddMMyy'),'_',Format(dateadd(day,6,StartDate),'ddMMyy')) as date
   from cte