如何在特定的时间跨度和周数之间动态创建日期?

时间:2016-01-12 07:07:29

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

我有以下客户表:

ID | StartDate  | WeekCount
1  | 01.12.2015 | 2
2  | 03.12.2015 | 4
3  | 06.06.2014 | 8

Startdate代表客户第一次访问的日期,WeekCount代表下次访问(每X周)

我想查询timepawn的下一个访问日期。

让我们说第一次访问是 03.12.2015 然后我查询 2016年3月所以预期日期应 03.03.2015 。< / p>

基本上是StartDate+WeekCount,然后是过滤器之间的日期。

2 个答案:

答案 0 :(得分:1)

我认为recursive CTE可以帮助您解决问题。

DECLARE @to_date DATETIME
SET @to_date = N'2016.03.01'

;WITH test_data AS(
    SELECT 1 AS id, CAST(N'2015.12.01' AS DATETIME) AS startDate, 2 AS weekCount
    UNION ALL
    SELECT 2 AS id, CAST(N'2015.12.03' AS DATETIME) AS startDate, 4 AS weekCount
    UNION ALL
    SELECT 3 AS id, CAST(N'2014.06.06' AS DATETIME) AS startDate, 8 AS weekCount
),
result_tbl AS(
    SELECT id, startDate, weekCount FROM test_data
    UNION ALL
    SELECT id, DATEADD(ww, R.weekCount, R.startDate), weekCount FROM result_tbl AS R
    WHERE R.startDate < @to_date
)

SELECT * FROM result_tbl
ORDER BY id

答案 1 :(得分:0)

如果数据类型为date / datetime

Select columns from your_table
where StartDate>='20160301' and StartDate<'20160401'