我的开始日期是2009 - 04 - 01(2009年4月4日),结束日期是getdate()。
我需要计算从开始日期到今天某些事情的每个日期。 我还需要将其分为两种情况:
案例1:如果是星期五,我需要回到347天,例如
select datediff(dw, '2010-11-22','2011-11-04')
每个星期五,然后执行一些选择。
案例2:如果它是从星期一到星期四再返回349天,例如
select datediff(dw, '2010-11-19','2011-11-03')
我怎么写这个,我需要执行的只是把它当作:
declare @startDate date
declare @endDate date
declare @dateHolder date
declare @tsID int
set @startDate = '2009-04-01'
set @endDate = getdate()
set datefirst 1;
while (select count (tsID) from #tempI)>0
begin
select top 1 @tsID = tsID from #tempI
while (select count (rateDate) from #tempI)>0
begin
select top 1 @dateHolder = rateDate from #tempI
case (select datename (dw, @dateHolder) = '5' then someColumn = @dateHolder - 347 as dateIneedToUseForMyFormula
case (select datename (dw, @dateHolder) = '1' or '2' or '3' or '4' then someColumn = @dateHolder - 349 as dateIneedToUseForMyFormula
-- here i don't know how to write the code, so i'll write pseudo
-- i have tsID rateDate and rate
-- i need to put in a new column (the value obtained from taking the value
-- from the column rate corresponding to the @dateHolder - the value from
-- the column rate corresponding to the @dateHolder - 347 or 349
-- depending on the case) * 100
end
delete from #tempI where @dateHolder = rateDate
end
delete from #tempI where @tsID = tsID
end
修改 我在评论中被问到要做什么,并且考虑到这个问题,我认为我并不清楚。我将复制粘贴我在评论中写的内容: “ 首先遍历列表中的所有tsID,在这样做之后迭代所有日期,从中减去349或347天的日期,然后检查放入新列的结果:'rate'的值与我的日期对应的列 - 'rate'列的值,对应于349或347天前的日期。这是针对每个id“
的所有日期执行的编辑2:预期输出
tsID rateDate rate calculated
1 2009-04-01 0.12 null
1 2009-04-02 0.14 null
1 2009-04-03 0.11 null
2 2009-04-01 0.01 null
2 2009-04-02 0.012 null
2 2009-04-03 0.43 null
. . . 347 days later or 349 depending
on what 2009-04-01 was
1 2010-03-16 0.454 (0.454 - 0.12)*100
1 2010-03-17 0.34 (0.34 - 0.14)*100
1 2010-03-18 0.9 (0.9 - 0.11)*100
then same for id 2.3...4...
答案 0 :(得分:1)
试试这个
Declare @start Date='2009-09-01', @end Date=getdate();
;With NumberSequence( Number ) as
(
Select @start as Number
union all
Select DATEADD(d,1,Number)
from NumberSequence
where Number < @end
)
Select
(CASE WHEN (datepart(dw,Number) =6) THEN DATEADD(d,-347,Number)
ELSE DATEADD(d,-349,Number)
END ) AS Date
From NumberSequence Option (MaxRecursion 10000)
答案 1 :(得分:0)
使用工作日的案例陈述:
Select Case
When WeekDAy(yourdate, 3) < 4 then datediff(dw, '2010-11-19','2011-11-03')
when WeekDAy(yourdate, 3) = 4 then datediff(dw, '2010-11-22','2011-11-04')
Else ...?... End