根据参数和最后一行日期更新临时表中的日期

时间:2016-09-26 11:04:35

标签: tsql lag

我正在尝试使用参数更新临时表中的日期并查看最后一行的日期。

DECLARE @multiDayCourseDaysBetween INT = 3;

CREATE TABLE #Courses(TempId INT IDENTITY(1,1)
                        , [Date] DATE
                        , CourseTypeId INT
                        , OrganisationId INT
                        , Reference VARCHAR(100)
                        , CreatedByUserId INT
                        , CourseTypeCategoryId INT
                        , TrainersRequired INT);

CREATE TABLE #TempDates(TempId INT
                        , [Date] DATE
                        , LagDate DATE);

INSERT INTO #Courses([Date])
Values('2016-06-01')

INSERT INTO #Courses([Date])
Values('2016-06-02')

INSERT INTO #Courses([Date])
Values('2016-06-03')

INSERT INTO #TempDates(tempId, [date], LagDate)
SELECT TempId, [Date]  
     , LAG(c.[Date],1) OVER (ORDER BY [Date]) as LagDate
FROM #Courses c

UPDATE #TempDates
SET [Date] = DATEADD(dd, @multiDayCourseDaysBetween, LAG([Date],1) OVER (ORDER BY [Date])) 
WHERE LagDate IS NOT NULL

但是我收到一个错误 - '窗口函数只能出现在SELECT或ORDER BY子句中。'

例如,原始日期将是

2016-06-01
2016-06-02
2016-06-03

但我需要他们成为

2016-06-01
2016-06-04
2016-06-07

基于3作为参数。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试将最后一个语句更改为以下内容:

WITH b AS (
SELECT
    TempId
    , [Date]
    , FIRST_VALUE([Date]) OVER (ORDER BY [Date]) as FirstDate
    , ROW_NUMBER() OVER (ORDER BY [Date]) AS rowRank
FROM
    #TempDates
)
UPDATE b
SET [Date] = DATEADD(day, (rowRank-1)* @multiDayCourseDaysBetween, FirstDate)
WHERE
    rowRank > 1;