T-SQL CTE自引用CROSS APPLY以前的行与日期有差距

时间:2015-02-24 17:55:52

标签: sql-server tsql common-table-expression union-all

我在SQL Server 2014中有一个可更新的日期值序列表(比如dbo.sequence)。日期是唯一的。

当有新的更新时,我希望在某些条件下将这些值分配到单独的表格中(例如dbo.distributed_values),例如如果dbo.sequence的先前值小于/大于当前dbo.sequence值,则会将其插入到dbo.distributed_values的指定列中,或在该列中变为NULL。

这是主要的想法:

;WITH
CTE_tbl (date, value, val_1, val_2, val_3)
AS (
SELECT ... FROM dbo.distributed_values  -- get latest values from database

UNION ALL

SELECT
   SEQ.date,
   SEQ.value,

   CASE
   WHEN ABS (SEQ.value - prev.value) >= 0.5
   THEN SEQ.value
   ELSE NULL
   END AS val_1,

   ...

   FROM dbo.sequence AS SEQ
   CROSS APPLY (SELECT * FROM CTE_tbl WHERE date = DATEADD(DAY, -1, SEQ.date)) AS prev
)

INSERT INTO dbo.distributed_values (...)
SELECT *
   FROM CTE_tbl
   ORDER BY date ASC
   OPTION (MAXRECURSION 1000)

似乎它主要起作用,但dbo.sequence包含间隙,所以我不能使用像date = DATEADD(DAY, -1, SEQ.date)这样的东西来正确绑定前一行。

2012-01-04
2012-01-05
2012-01-06
2012-01-09
2012-01-10
2012-01-11

如果日期空白,如何正确绑定以前的值?

UPD: 顺便说一下,我试过LAG ... OVER条款中不能使用WHERE。它可以在某种程度上使用吗?

1 个答案:

答案 0 :(得分:1)

添加另一个CTE并在递归CTE中使用它,如下所示:

;WITH
SequenceWithPrevious AS(
    SELECT * 
        ,PrevValue = LAG(value,1,NULL) OVER (ORDER BY SEQ.date)
        ,Prevdate = LAG(date,1,NULL) OVER (ORDER BY SEQ.date)
    FROM dbo.sequence AS SEQ
),
CTE_tbl (date, value, val_1, val_2, val_3)
AS (
SELECT ... FROM dbo.distributed_values  -- get latest values from database

UNION ALL

SELECT  ...
   FROM SequenceWithPrevious AS SEQ
   CROSS APPLY (SELECT * FROM CTE_tbl WHERE date = SEQ.PrevDate) AS prev
)

INSERT INTO dbo.distributed_values (...)
SELECT *
   FROM CTE_tbl
   ORDER BY date ASC
   OPTION (MAXRECURSION 1000)