如何使用SQL查询选择日期和每两周的付款期限

时间:2014-06-23 20:27:23

标签: sql-server tsql sql-server-2008-r2

如何在此日期到2010年初之前选择6/20/2014和每个支付日期(每两周一次)?我还希望能够在此日期到2020年底之后选择6/20/2014和每个支付日期(每2周)。

谢谢!

2 个答案:

答案 0 :(得分:2)

下面的SQL可以为您提供问题第一部分的答案。可以使用相同的原则来获得第二部分的答案。

declare @startDate as date = '20140620';

with myCte1 as
(
    select @startDate as dt
    union all
    select DATEADD(week, -2, dt)
    from myCte1
    where dt > '20100112'
)

select m.dt
from myCte1 as m
option (maxrecursion 1000)

答案 1 :(得分:1)

创建Numbers table

SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO NumbersTest
FROM sys.objects s1
CROSS JOIN sys.objects s2
ALTER TABLE NumbersTest ADD CONSTRAINT PK_NumbersTest PRIMARY KEY CLUSTERED (Number)

然后

declare @startDate date = '6/20/2014'

--Dates from 1/1/2010 to 6/20/2014
select DATEADD(wk, -2 * (n.Number - 1), @startDate)
from NumbersTest n
where DATEADD(wk, -2 * (n.Number - 1), @startDate) >= '1/1/2010'

--Dates from 6/20/2014 to 12/31/2020
select DATEADD(wk, 2 * (n.Number - 1), @startDate)
from NumbersTest n
where DATEADD(wk, 2 * (n.Number - 1), @startDate) <= '12/31/2020'

SQL Fiddle